应用关闭后,广播接收器仍在运行-Android

应用关闭后,广播接收器仍在运行-Android

问题描述:

我正在使用该代码可以完美运行,并且完全符合我的要求.

The code works perfectly, and does exactly what I want.

我有1个问题.

我希望我的应用程序在后台运行,但是当它关​​闭时,我希望它停止拦截SMS消息.

I want my app to run in the background, but when it's closed I want it to stop intercepting SMS messages.

我的问题是,为什么我的应用在关闭后为什么仍在拦截SMS消息?

My question is, why is my app still intercepting SMS messages after it's been closed?

我想我必须找到一个关闭"处理程序,然后关闭广播接收器. (如果有关闭"事件处理程序..?).

I guess I have to find a "on close" handler and close the Broadcast Receiver then. (If there is a "on close" event handler..?).

如果有人能提供一些见解,我将不胜感激.谢谢!

If anyone can provide some insight I would be very grateful. Thanks!

通过将BroadcastReceiver放入清单中,默认情况下它始终处于活动状态.因此,如果您希望它仅在显示Activity时运行,那么您将希望在Activity恢复/暂停时启用/禁用BroadcastReceiver:

By putting your BroadcastReceiver in your Manifest, it, by default, is always active. Therefore if you want it to only run while your Activity is shown, you'll want to enable/disable your BroadcastReceiver when your Activity resumes/pauses:

public void onResume()
{
    ComponentName component=new ComponentName(this, TextMessageReceiver.class);
    getPackageManager()
        .setComponentEnabledSetting(component,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

public void onPause()
{
    ComponentName component=new ComponentName(this, TextMessageReceiver.class);
    getPackageManager()
        .setComponentEnabledSetting(component,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}

另一种方法是在Activity中声明您的BroadcastReceiver,然后在相同的生命周期事件中调用registerReceiverunregisterReceiver.

The alternative, is to declare your BroadcastReceiver in your Activity and then call registerReceiver and unregisterReceiver in the same lifecycle events.