Today, I read the textbook and sorted out the broadcast content in Android.
What we write is actually a broadcast receiver. First we have to write a class that inherits broadcastreceiver and then rewrite the onreceive method in it. Some of our operations are written in this method. We can implement many functions for broadcasting. For example, we can monitor battery power, spam messages, and blacklist. There are two methods for registering: the first method isCodeRegister. The second is to register in androidmanifest. xml.
The difference between the two registration methods is that the first registration can enable broadcast registration or stop broadcast. Method 2 registration means that even if we quitProgramBut the broadcast receiver we write is still running and will continue to receive the broadcast. If we listen to the battery, We have to receive the broadcast at the moment, that is, use the second method to register, but this method consumes and consumes both the battery power and the processor of the mobile phone. So we have time to use the code registration method.
However, these two registration methods must be set in androidmanifest. xml:
<Uses-Permission Android: Name = "android. Permission. receive_sms"> </uses-Permission>
Code registration:
Private Static final string sms_action = "android. provider. telephony. sms_received"; // type of broadcast received
Smsbroadcast = new smsbroadcast (); // generate a broadcastreceiver object
Intentfilter = new intentfilter (); // generate an intentfilter object
Intentfilter. addaction (Sms_action); // Add an action for intentfilter
Mainactivity. This. registerreceiver (smsbroadcast, intentfilter); // register the broadcastreceiver object to the system.
Code to cancel registration:
Mainactivity. This. unregisterreceiver (smsbroadcast );
Register in androidmanifest. xml:
<Cycler Android: Name = ". smsbroadcast"
Android: Label = "@ string/app_name">
<Intent-filter> //This is to filter the broadcast type.
<Action Android: Name = "android. provider. telephony. sms_received"/>
</Intent-filter>
</Cycler>
Such a simple broadcast is written.