Android notes. BroadcastReceiver, broadcastreceiver
Broadcast is a mechanism widely used to transmit information between applications. BroadcastReceiver is a component that filters and receives and responds to sent broadcasts. BroadcastReceiver is essentially a global listener used to listen to global broadcast messages of the system and receive specified broadcasts. Therefore, it can easily implement communication between different components in the system. The knowledge point structure of BroadcastReceiver is as follows:I. send and receive broadcasts1. Send BroadcastThe broadcast is sent by calling Context. sendBroadcast (), Context. sendOderedBroadcast (): (1) Context. sendBroadcast (Intent intent): used to send a normal broadcast. The intent parameter indicates the conditions required by the broadcast receiver to receive the broadcast and the data transmitted by the broadcast. (2) Context. sendOderedBroadcast (Intent intent, String receiverPermission): used to send ordered broadcasts. The intent parameter is the same as above. receiverPermission indicates the permission to receive the broadcast.2. Receive BroadcastThe BroadcastReceiver component is used to filter and receive the sent broadcast and respond to the specified broadcast. Generally, a broadcast can be received by multiple broadcast recipients subscribed to the Intnet. Just like a broadcast station, it can be listened to by multiple listeners. To start BroadcastReceiver, follow these steps: (1) Create an Intent and specify features of BroadcastReceiver; (2) Call sendBroadcast () (send normal broadcast) or sendOrderBroadcast () (send ordered broadcast) of Context) method to send the broadcast and trigger the specified BroadcasttReceiver. Therefore, when an application sends a broadcast, all BroadcastReceiver matching the Intent may be started.Ii. Broadcast Classification1. Normal BroadcastIt is completely asynchronous and can be received by all receivers at the same time (logically). The message transmission efficiency is relatively high. However, the receiver cannot pass the processing result to the next receiver, and cannot terminate the Broadcast Intent propagation.2. Ordered BroadcastThe receiver of the broadcast receives the broadcast in the pre-declared priority order. The receiver of an ordered broadcast can terminate the broadcast (by calling the abortBroadcast () method). Once the broadcast is terminated, the subsequent receiver cannot receive the broadcast. In addition, the receiver of the broadcast can pass data to the next receiver (through the setResultExtras (Bundle bundle) method ).3. BroadcastReceiver application development stepsBroadcastReceiver itself does not implement a graphical user interface, but when it receives a message, it can start the Activity as a response, or notify the user through icationicationmanager, or start the Service.1. Create a broadcast Receiver. Implement a subclass that inherits from the BroadcastReceiver base class and implement the onReceiver () method in it;
- Public ClassMyBroadcastReceiverExtendsBroadcastReceiver
- {
- Public VoidOnReceiver (Context context, Intent intent ){
- }
- }
In the onReceiver () method, an Intent parameter is received to obtain the data carried by the broadcast, and a Service can be started to process time-consuming tasks.
2. Send a broadcast and specify the Intent attribute of the broadcast.After the broadcast receiver is registered, it does not run directly. It must be called only after receiving the broadcast. Therefore, broadcast must be sent first, and then the sendBroadcast (Intent intent) or sendOrderedBroadcast (Intent intent, String receiverPermission) of Context must be called in Activity or Service.
3. register the broadcast receiver to specify which broadcast it receives.After the broadcast receiver is created, it cannot be used immediately. You must register a specified broadcast for it (broadcast receiver), just as if we have a radio, you must also select which channel to listen. (1) static registration: it refers to registration in the AndroidManifest. xml file.
- <Cycler android: name = ". MyBroadcastReceiver">
- <Intent-filter>
- <Action
- Android: name = "com. jiangdongguo. android. myBroadcastReceover">
- <Action/>
- </Intent-filter>
- </Cycler>
(2) Dynamic Registration: You need to dynamically specify the broadcast address in the Code and register it. It is usually called by ContextWrapper in Activity or Service.
- Register the registerReceiver (BroadcastReceiver receiver, IntentFilter filter) method.
- MyBroadcastReceiver myBroadcastReceiver =NewMyBroadcastReceiver ();
- IntentFilter filter =NewIntentFilter ("com. jiangdongguo. android. myBroadcastReceover"); // specifies the broadcast to be received.
- RegisterReceiver (myBroadcastReceiver );
Specifically, MyBroadcastReceiver is the base class BroadcastReceiver subclass. After registration, you can receive the corresponding Broadcast message. Once a Broadcast (Broadcast) event occurs, the system will create a corresponding BroadcastRecevier instance and automatically trigger its onReceiver () method, after the onReceiver () method is executed, the BroadcastReceiver instance is destroyed.
Iii. Source Code practiceImplementation: Enable a broadcast in the Activity. The broadcast receiver receives the broadcast and responds to the broadcast.
1. MyBroadcastReceiver. java:Inherited from the BroadcastReceiver subclass-broadcast receiver, used to receive specified broadcasts and respond accordingly.
- Package com. example. mybroadcast;
- Import android. content. BroadcastReceiver;
- Import android. content. Context;
- Import android. content. Intent;
- Import android. widget. Toast;
- /* BroadcastReceiver subclass
- * Used to receive the specified sending broadcast */
- Public class MyBroadcastReceiver extends BroadcastReceiver {
- @ Override
- Public void onReceive (Context arg0, Intent arg1 ){
- Toast. makeText (arg0, "I am BroadcastReceiver, and I have received the broadcast sent! ", Toast. LENGTH_SHORT). show ();
- }
- }
Note: You can obtain the data carried by Intent in the onReceiver () method, or start a Service to execute time-consuming tasks.
2. MainActivity. javaThe main Activity, used to send a broadcast, or can register the broadcast receiver instead of the AdroidManifest. xml project file.
- Package com. example. mybroadcast;
- Import android. app. Activity;
- Import android. content. Intent;
- Import android. content. IntentFilter;
- Import android. OS. Bundle;
- Import android. view. View;
- Import android. view. View. OnClickListener;
- Import android. widget. Button;
- Public class MainActivity extends Activity {
- Private Button sendBroad;
- @ Override
- Protected void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. main );
- /* 1. Method 2: register a broadcast receiver */
- MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver ();
- IntentFilter filter = new IntentFilter ("com. jiangdongguo. Android. BroadcastReceiver ");
- RegisterReceiver (myBroadcastReceiver, filter );
- SendBroad = (Button) findViewById (R. id. send );
- SendBroad. setOnClickListener (new OnClickListener (){
- Public void onClick (View v ){
- /* 2. Send a broadcast and specify its action attribute */
- // A. Specify the broadcast action attribute
- Intent intent = new Intent ("com. jiangdongguo. Android. BroadcastReceiver ");
- // B. Send Broadcast
- SendBroadcast (intent );
- }
- });
- }
- }
3. AndroidManifest. xml project file. The role here is to add registration for BroadcastReceiver.
- <? Xml version = "1.0" encoding = "UTF-8"?>
- <Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
- Package = "com. example. mybroadcast"
- Android: versionCode = "1"
- Android: versionName = "1.0" type = "codeph" text = "/codeph">
- <Uses-sdk
- Android: minSdkVersion = "8"
- Android: targetSdkVersion = "14"/>
- <Application
- Android: allowBackup = "true"
- Android: icon = "@ drawable/ic_launcher"
- Android: label = "@ string/app_name"
- Android: theme = "@ style/AppTheme">
- <Activity
- Android: name = ". MainActivity"
- Android: label = "@ string/app_name">
- <Intent-filter>
- <Action android: name = "android. intent. action. MAIN"/>
- <Category android: name = "android. intent. category. LAUNCHER"/>
- </Intent-filter>
- </Activity>
- <! -- Broadcast receiver Registration Method 1: which broadcast is received -->
- <! -- <Javaser android: name = ". MyBroadcastReceiver">
- <Intent-filter>
- <Action android: name = "com. jiangdongguo. Android. BroadcastReceiver"/>
- </Intent-filter>
- </Explorer> -->
- </Application>
- </Manifest>
Effect demonstration: source code analysis: (1) if it is determined that a time-consuming operation needs to be completed based on broadcast, you can use Intent to start a Service to complete the operation. You should not consider using a new thread to perform time-consuming operations. Because the life cycle of BroadcastReceiver itself is very short, it may occur that the subthread may not end, And BroadcastReceiver has exited. (2) If the process in which the broadcast receiver is located is finished, although there are new threads started by the user in the process, because the process does not contain any active components, therefore, the system may give priority to thread termination when the memory is insufficient. In this way, the subthread started by BroadcastReceiver cannot be executed completely.