Android BroadcastReceiver registration and de-registration

Speaking of this problem is very simple, as long as the registration and anti-registration appear in pairs, it seems that many textbooks are introduced in this way. However, in actual development, it is still very important to grasp the timing of broadcast registration and de-registration.

Regarding the timing of BroadcastReceiver registration and de-registration, there are mainly the following points:

onCreate-onDestroy (even if the page is not displayed, the broadcast can still be accepted)
onResume-onPause (that is, the broadcast can only be accepted when the page is displayed)
onStart-onStop

http://stackoverflow.com/questions/21136464/when-to-use-unregisterreceiver-onpause-ondestroy-or-onstop


When registering for broadcast, the problem often encountered is that if you repeatedly cancel the broadcast processing function, an error will be reported and the process will crash. Generally speaking, a variable can be used to save whether the broadcast processing is logged out, and mark it as false whenever logging out. If false is encountered when logging out again, he will not be logged out.

I have encountered an exception several times, which prompted me that my BroadcastReceiver was deregistered many times, causing the system to die abnormally. It took a long time to check the code to find the reason. .

For example, I used to deregister broadcast in the finish method before, but the finish method may be called multiple times, causing BroadcastReceiver to be deregistered multiple times. 

In addition, you need to pay attention to what contex (context) you use to register the broadcast, you must use it to deregister.

For example, you call getApplicationContext() to register and getApplicationContext() to delete. You cannot directly unregisterReceiver(mFinishReceiver); and registerReceiver(mFinishReceiver, filter); may not be found.

In addition, regarding BroadcastReceiver also involves security issues, please refer to:

http://blog.csdn.net/t12x3456/article/details/9256609

Guess you like

Origin blog.csdn.net/lxxlxx888/article/details/53956010