I. Introduction of the broadcasting mechanism
Each application in the 1.Android can register and listen for broadcasts of interest to them. These broadcasts can be either system or from other programs.
2. Type of broadcast:
- Orderly broadcast: is a synchronous broadcast, after the broadcast, only one broadcast receiver can receive the broadcast at the same time, and wait for the receiver, processing the completion of logic, the broadcast will continue. So the broadcast receiver has a priority division, the high priority of nature can first obtain broadcast information. Priority settings can be set through the properties
<intent-filter android:priority="1000"> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/></intent-filter>
- Standard broadcast: is a completely asynchronous broadcast, after the broadcast, all the broadcast reception can almost simultaneously obtain the broadcast information, there is no priority between them.
Second, reception system broadcast
There are many system-level broadcasts built into Android, and we can listen to these broadcasts to get system information in the app. For example, get the phone boot information, access to mobile phone network information. Where we need to register our own broadcast receivers in the application, there are two ways to register a broadcast reception
1. Dynamic registration: The registration of the broadcast receiver in the appropriate location through the code, and the cancellation registration of the broadcast reception. First create the Intentfilter instance and set its action, because each broadcast of the system will have an action value. For example, when a device's network changes, it emits a broadcast with the action value: "Android.net.conn.CONNECTIVITY_CHANGE". Then the broadcast receiver is registered via Registerreceiver (broadcastreceiver,filter).
filternew IntentFilter( ); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); new NetWorkChangeReceiver() ; registerReceiver(netWorkChangeReceiver ,filter) ; Log.i("onCreate","注册广播接收器");
unregisterReceiver(netWorkChangeReceiver);
Dynamic registration broadcasts have the freedom to control registration and logoff and have a great advantage in terms of flexibility, but there is a drawback that they must be started before they can receive broadcasts.
2. Static registration: Solve the disadvantages of dynamic registration, you can complete the registration when the program is installed, and listen to the broadcast. You first create an instance of the inherited Broadcastreceiver, and override the OnReceive () method (Note that you cannot do too much time-consuming operations in the OnReceive () method). We then need to register the broadcast receiver in the Androidmanifest.xml. The specific code is as follows:
Public class myreceiver extends broadcastreceiver { Private Static FinalString Parames ="Parames"; Public Myreceiver() {LOG.I ("Broadcastdemo","Myreceiver ()"); }/** * Send custom, Standard broadcast * @param context * @param parames */ Public Static void Sendbroadcast(Context context,string Parames) {Intent Intent =NewIntent ("Com.example.chf.broadcast_test") ; Intent.putextra (Parames, parames); Context.sendbroadcast (Intent); }/** * Send local broadcast * Local broadcast receiver, only through dynamic registration, because the local broadcast is to receive after the program started * @param context * @param Parames * / Public Static void Sendlocalbroadcast(context context, String parames) {Localbroadcastmanager Localbroadcastmanager = localbroadcastmanager.getinstance (context);//Dynamic registration of local broadcast receiversIntentfilter filter =NewIntentfilter ("Com.example.chf.broadcast_test") ; Myreceiver Myreceiver =NewMyreceiver (); Localbroadcastmanager.registerreceiver (Myreceiver,filter); Intent Intent =NewIntent ("Com.example.chf.broadcast_test") ; Intent.putextra (Parames, parames); Localbroadcastmanager.sendbroadcast (Intent); }@Override Public void OnReceive(context context, Intent Intent) {if(Intent! =NULL) {String parames = Intent.getstringextra (parames); Toast.maketext (Context,parames,toast.length_short). Show (); LOG.I ("Receive broadcast information", parames); } }}
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android" package ="Com.example.chf.thefirstlinecodeofandroid"> .....<receiverandroid:name=". Myreceiver "android:enabled=" true "android:exported=" true " > <intent-filter android:priority="+"> <action android:name="Com.example.chf.broadcast_test"/> </intent-filter> </receiver> </Application></manifest>
The properties in Androidmanifest.xml set android:enable and the role of android:exported.
* android:enabled = "true": the system will automatically instantiate the broadcast receiver after the program is installed
* android:enabled = "false": the system does not automatically instantiate the broadcast receiver after the program is installed.
* android:exported = "True" allows broadcast receivers to receive broadcasts from external applications
* android:exported = "false" does not allow broadcast receivers to receive broadcasts from external applications
See
Http://developer.android.com/intl/zh-cn/guide/topics/manifest/receiver-element.html
An interesting question has been found: When I create a broadcast receiver to get the status of the network, and set the broadcast receiver to static registration, but after the program exits, no matter how the current network state is changed, the broadcast information cannot be obtained. However, if you are a custom broadcast receiver and have been statically registered, you can get customized broadcast information even if the program is in an exiting state.
Main reasons:
Android 3.1 Start the system sets the flag parameter for each intent in the intent-related broadcast, respectively:
* Flag_include_stopped_packages (contains a package that has been stopped)
* Flag_exclude_stopped_packages (does not contain a package that has been stopped)
Since the Android3.1 system has started, the system itself will increase the number of all apps that are currently running in a tracking state. When sending a broadcast, no matter what type of broadcast, the system defaults to its FLAG value of flag_exclude_stopped_packages, resulting in even a statically registered broadcast receiver, which cannot receive broadcasts if the app is in a process exit state
See Http://developer.android.com/about/versions/android-3.1.html#launchcontrols
For custom broadcasts, we can set the FLAG value of the intent to flag_include_stopped_packages so that the statically registered broadcast receiver can receive the broadcast even if the app exits, and the process is started, However, the broadcast receiver is re-created at this time.
Third, send a custom broadcast
1. Sending standard broadcasts
Intent intent = new Intent("com.example.chf.broadcast_test";intent.putExtra;context.sendBroadcast(intent);
2. Send an ordered broadcast
An ordered broadcast is sent through Sendorderedbroadcast (Intent Intent, String receiverpermission). Broadcast receiver android:priority= "" The higher the priority of the receive broadcast, the lower priority broadcast sink can wait for a high-priority processing logic to receive the broadcast. A broadcast receiver with high priority, however, can truncate the broadcast through the Abortbroadcast () method so that the next broadcast receiver is not able to receive information. At the same time high priority can also be setresultdata () and other methods to reset the broadcast content, so that the next broadcast receiver through Getresultdata () will get different information
Public class myreceiver extends broadcastreceiver { Private Static FinalString Parames ="Parames"; Public Myreceiver() {LOG.I ("Broadcastdemo","Myreceiver ()"); } ....../** * Send an ordered broadcast * @param context * @param parames */ Public Static void Sendorderedbroadcast(context context, String parames) {Intent Intent =NewIntent ("Com.example.chf.broadcast_test") ; Intent.putextra (Parames, parames); Context.sendorderedbroadcast (Intent,NULL); }@Override Public void OnReceive(context context, Intent Intent) {if(Intent! =NULL) {String parames = Intent.getstringextra (parames); Toast.maketext (Context,parames,toast.length_short). Show (); LOG.I ("Receive broadcast information","Myreceiver"+parames);//abortbroadcast ();Setresultdata ("broadcast when modified from Myreceiver ()"); } }}
publicclass SecondReceiver extends BroadcastReceiver { publicSecondReceiver() { } @Override publicvoidonReceive(Context context, Intent intent) { String parames = getResultData() ; Log.i("接收广播信息","SecondReceiver"+parames) ; }}
Configure Androidmanifest.xml, and set property precedence
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android" package ="Com.example.chf.thefirstlinecodeofandroid"> ......<receiverandroid:name=". Myreceiver "android:enabled=" true "android:exported=" true "> <intent-filter android:priority="+"> <action android:name="Com.example.chf.broadcast_test" /> </intent-filter> </receiver> <receiverandroid:name=". Secondreceiver "android:enabled=" true "android:exported=" true " > <intent-filter android:priority="All"> <action android:name="Com.example.chf.broadcast_test" /> </intent-filter> </receiver> </Application></manifest>
The test results are
Iv. use of local broadcasts
By acquiring Localbroadcastmanager, local broadcasts are sent through their send sendbroadcast (intent), and local broadcasts only allow dynamic registration.
Local Broadcast advantages:
* 1. Do not worry about the broadcast information sent by the application will be obtained by other applications, ensuring the security of the data
* 2. Other applications may not be able to send broadcasts at will, allowing the application local broadcast receivers to be received, so you don't have to worry about them being exploited
* 3. More efficient than global broadcasts sent by the system
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context) ; //动态注册 本地广播接收器 new IntentFilter("com.example.chf.broadcast_test") ; new MyReceiver() ; localBroadcastManager.registerReceiver(myReceiver,filter); new Intent("com.example.chf.broadcast_test") ; intent.putExtra(PARAMES ,parames) ; localBroadcastManager.sendBroadcast(intent);
Note that dynamic broadcasts can only be registered dynamically and are registered and sent using Loaclbroadcastmanager.
Ps: Little brother, the text will inevitably have some loopholes, only as a note use. If there is a serious error, please leave a message to help me improve. At the same time we can make a friend.
Learn about Android Radio