In the development of Android mobile apps, Broadcastreceiver is needed to listen for broadcast messages. In customizing the Broadcastreceiver, you need to register it, there are two ways to register it:
One is to register in the code, the method of registration is Registerreceiver (receiver,filter)(with the activity of the instance to invoke), take Registration method: Unregisterreceiver (receiver), If a broadcastreceiver is used to update the UI (User Interface), then this method is usually used to register , register the activity when it is activated, and cancel the registration after the activity is not visible ;
The other is to register in the Androidmanifest .
Registering with the Code
New Intentfilter ("Android.provider.Telephony.SMS_RECEIVED"); New incomingsmsreceiver (); Registerreceiver (receiver, filter);
in the Androidmanifest.xml file Register in the <application> node
< receiver android:name = ". Incomingsmsreceiver " > < Span style= "color: #800000;" >intent-filter > < action android:name = " Android.provider.Telephony.SMS_RECEIVED " /> </ intent-filter > </ receiver >
After registration, you can send the broadcast, using Context.sendbroadcast (), Context.sendorderedbroadcast (), or context.sendstickybroadcast () to implement the Receive-side code:
Public class extends broadcastreceiver { @Override publicvoid onreceive (context context, Intent Intent) { //todo ... Receive a broadcast, do your own business }}
Difference
- After registering in androidmanifest, regardless of whether the application is active, will listen , such as a program when listening to memory usage, when installed on the phone, regardless of the application is in what state, Will execute the contents of the listening method.
After registering in code, when the application shuts down, it is no longer listening . We read that whether the application is power-saving determines the popularity of the application, so for receiver that does not need to listen after the program shuts down, registering in the code is undoubtedly a wise choice.
I'm the dividing line of the king of the Land Tiger.