Android notes. BroadcastReceiver, broadcastreceiver

Source: Internet
Author: User

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;

  1. Public ClassMyBroadcastReceiverExtendsBroadcastReceiver
  2. {
  3. Public VoidOnReceiver (Context context, Intent intent ){
  4. }
  5. }
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.
  1. <Cycler android: name = ". MyBroadcastReceiver">
  2. <Intent-filter>
  3. <Action
  4. Android: name = "com. jiangdongguo. android. myBroadcastReceover">
  5. <Action/>
  6. </Intent-filter>
  7. </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.
  1. Register the registerReceiver (BroadcastReceiver receiver, IntentFilter filter) method.
  2. MyBroadcastReceiver myBroadcastReceiver =NewMyBroadcastReceiver ();
  3. IntentFilter filter =NewIntentFilter ("com. jiangdongguo. android. myBroadcastReceover"); // specifies the broadcast to be received.
  4. 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.
  1. Package com. example. mybroadcast;
  2. Import android. content. BroadcastReceiver;
  3. Import android. content. Context;
  4. Import android. content. Intent;
  5. Import android. widget. Toast;
  6. /* BroadcastReceiver subclass
  7. * Used to receive the specified sending broadcast */
  8. Public class MyBroadcastReceiver extends BroadcastReceiver {
  9. @ Override
  10. Public void onReceive (Context arg0, Intent arg1 ){
  11. Toast. makeText (arg0, "I am BroadcastReceiver, and I have received the broadcast sent! ", Toast. LENGTH_SHORT). show ();
  12. }
  13. }
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.
  1. Package com. example. mybroadcast;
  2. Import android. app. Activity;
  3. Import android. content. Intent;
  4. Import android. content. IntentFilter;
  5. Import android. OS. Bundle;
  6. Import android. view. View;
  7. Import android. view. View. OnClickListener;
  8. Import android. widget. Button;
  9. Public class MainActivity extends Activity {
  10. Private Button sendBroad;
  11. @ Override
  12. Protected void onCreate (Bundle savedInstanceState ){
  13. Super. onCreate (savedInstanceState );
  14. SetContentView (R. layout. main );
  15. /* 1. Method 2: register a broadcast receiver */
  16. MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver ();
  17. IntentFilter filter = new IntentFilter ("com. jiangdongguo. Android. BroadcastReceiver ");
  18. RegisterReceiver (myBroadcastReceiver, filter );
  19. SendBroad = (Button) findViewById (R. id. send );
  20. SendBroad. setOnClickListener (new OnClickListener (){
  21. Public void onClick (View v ){
  22. /* 2. Send a broadcast and specify its action attribute */
  23. // A. Specify the broadcast action attribute
  24. Intent intent = new Intent ("com. jiangdongguo. Android. BroadcastReceiver ");
  25. // B. Send Broadcast
  26. SendBroadcast (intent );
  27. }
  28. });
  29. }
  30. }
3. AndroidManifest. xml project file. The role here is to add registration for BroadcastReceiver.
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
  3. Package = "com. example. mybroadcast"
  4. Android: versionCode = "1"
  5. Android: versionName = "1.0" type = "codeph" text = "/codeph">
  6. <Uses-sdk
  7. Android: minSdkVersion = "8"
  8. Android: targetSdkVersion = "14"/>
  9. <Application
  10. Android: allowBackup = "true"
  11. Android: icon = "@ drawable/ic_launcher"
  12. Android: label = "@ string/app_name"
  13. Android: theme = "@ style/AppTheme">
  14. <Activity
  15. Android: name = ". MainActivity"
  16. Android: label = "@ string/app_name">
  17. <Intent-filter>
  18. <Action android: name = "android. intent. action. MAIN"/>
  19. <Category android: name = "android. intent. category. LAUNCHER"/>
  20. </Intent-filter>
  21. </Activity>
  22. <! -- Broadcast receiver Registration Method 1: which broadcast is received -->
  23. <! -- <Javaser android: name = ". MyBroadcastReceiver">
  24. <Intent-filter>
  25. <Action android: name = "com. jiangdongguo. Android. BroadcastReceiver"/>
  26. </Intent-filter>
  27. </Explorer> -->
  28. </Application>
  29. </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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.