问题
I'm using some code from this tutorial on how to receive SMS messages:
The code works perfectly, and does exactly what I want.
I am having 1 issue with it.
I want my app to run in the background, but when it's closed I want it to stop intercepting SMS messages.
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!
回答1:
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.
回答2:
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
回答3:
i would say override OnTerminate() on your application object and unregister your reciever there.
@Override
public void onTerminate() {
unregisterReceiver(mybroadcast);
super.onTerminate();
}
来源:https://stackoverflow.com/questions/16429354/broadcast-receiver-still-running-after-app-close-android