Broadcast Receiver Still Running after app close - Android

倖福魔咒の 提交于 2019-12-03 08:50:45

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);
}

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

ive looked around on here and this is the conclusion ive come to

try{
        unregisterReceiver(mybroadcast);
    }catch(IllegalArgumentException e){
        Log.d("reciever",e.toString());
    }

i would say override onDestroy() and put it in there

i would say override OnTerminate() on your application object and unregister your reciever there.

@Override
public void onTerminate() {
    unregisterReceiver(mybroadcast);
    super.onTerminate();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!