Broadcast usage in Android 17th

Source: Internet
Author: User

Broadcast usage in Android 17th

Broadcast is a mechanism widely used to transmit information between applications. Broadcast in android is used to listen to system events or application events! Broadcast in android includes normal broadcast, ordered broadcast, and asynchronous broadcast (viscous broadcast )!

The broadcast has both resident and non-resident broadcasts. Resident broadcasts are registered in xml. When the application is closed, if the corresponding broadcast is sent, the broadcast receiver can still be activated. A very resident broadcast is registered in the Code. When the application is closed, the broadcast is canceled, we can register the broadcast in the onCreate or onResume method in the Activity, and then cancel the registration broadcast in the onDestory or onPause method;

Note: If the broadcast is not resident, you must cancel the registration after the application is closed. Otherwise, an exception is thrown !!

Normal Broadcast Transmission

How to send normal broadcasts:

SendBroadcast (Intent intent): intent table. All Intent matching the broadcast can receive the broadcast information.

SendBroadcast (intent, String receiverPermission); intent is the same as above. receiverPermission indicates the permission. Broadcast With the matched permission can receive the corresponding broadcast. If it is null, it indicates the request without permission!

1. Use sendBroadcast (Intent intent) to send broadcasts

1) register a non-resident broadcast through code:

// Define two broadcast receivers: BroadcastReceiver receiver1 = new BroadcastReceiver () {@ Overridepublic void onReceive (Context context, Intent intent) {System. out. println ("receiver1 started! ") ;}}; BroadcastReceiver receiver2 = new BroadcastReceiver () {@ Overridepublic void onReceive (Context context, Intent intent) {System. out. println (" receiver2 started! ") ;};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // register broadcast IntentFilter filter = new IntentFilter (); filter. addAction ("com. xin. action. broadcast "); registerReceiver (receiver1, filter); registerReceiver (receiver2, filter) ;}@ Overrideprotected void onPause () {super. onPause (); // cancel the registration of the broadcast unregisterReceiver (receiver1); unregisterReceiver (receiver2 );}
Code registration is a very resident broadcast. We need to cancel the registration broadcast in the corresponding lifecycle of the Activity: unregisterReceiver

2) register a resident broadcast through an xml file. At this time, MyBroadcast1 and MyBroadcast2 are two broadcast classes:

public class MyBroadcast1 extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {System.out.println("MyBroadcast1 started!");}}
public class MyBroadcast2 extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {System.out.println("MyBroadcast2 started!");}}

Add:

        
             
                              
          
         
             
                              
          
 
The IntentFilter in the Code is the same as the intent-filter in the xml file, both of which are Intent, indicating which broadcast recipients can receive the broadcast sent by intent (String actionName!

3) broadcast sending: the broadcast with the intent that matches it will be activated

Intent intent=new Intent("com.xin.action.broadcast");sendBroadcast(intent);
Output result: MyBroadcast1 started, MyBroadcast2 started !!

Ii. Use sendBroadcast (intent, String receiverPermission) to send broadcasts

The introduction of the second parameter is shown above. It refers to a permission. We need to declare a permission in AndroidManifest. xml:

 
There are also a lot of attributes available for us to choose from. You can learn about them by yourself;

This permission is required for both the sender and receiver:

The sender and receiver use this permission:

 
Send broadcast via method: sendBroadcast (intent, "com. xin. permission"); the second parameter indicates the permission name we defined

The receiver declares the broadcast permission:

        
             
                              
          
 
In this way, the broadcast with the permission is defined. We need to define the permission for both the sender and receiver, otherwise the message cannot be sent!

Note that using sendBroadcast (intent, "com. xin. permission "); the sent broadcast does not need to add android: permission to the receiver to receive the broadcast. The test shows that the broadcast can be received without adding this parameter:

        
             
                              
          
 

Ordered Broadcast Transmission

As the name suggests, ordered broadcasting means that the broadcast is sent in order. It defines the android: priority as the priority for ordered sending. The higher the priority, the higher the priority, indicates that it receives a high broadcast level. android: priority generally ranges from-1000 to 1000;
The difference between ordered broadcast and normal broadcast:

The difference between ordered broadcast and unordered broadcast: After we send unordered broadcast, we don't know who will receive it first, let alone don't send it to another one after receiving it. Ordered broadcast can achieve this by setting priority to determine the order of broadcast recipients.

Sending method of ordered broadcast:

SendOrderedBroadcast (intent, receiverPermission );

SendOrderedBroadcast (intent, receiverPermission, resultReceiver,

Scheduler, initialCode, initialData, initialExtras)

Intent, broadcast, all matching this intent will receive broadcast from the receiver.

ReceiverPermission this is the permission, and a receiver must hold it to receive your broadcast. If it is null, the request is not permitted.
ResultReceiver you BroadcastReceiver as the final broadcast receiver.
Schedule a Custom Handler to schedule the resultReceiver callback. If it is null, the main thread in the context will be held.
InitialCode is the initial value of a result code. Usually Activity. RESULT_ OK. This value is-1; it can also be other int types, such as 0, 1, 2;
InitialData is the initial value of the result data. It is usually null, which is of the String type;
InitialExtras is an additional initial value of the result. Normally it is null, Which is Bundle;

Note the following for ordered broadcast:

1. The broadcast level can be classified as-1000 to 1000. The higher the value, the higher the priority;
2. The same-level reception is random and broadcast is received at a lower level;
3. The same-level receiver is random. If the receiver receives the broadcast first and truncates the broadcast, the receiver with exceptions at the same level cannot receive the broadcast. The method of truncation the broadcast is as follows: abortBroadcast ();
4. The broadcast can be truncated to continue propagation. After receiving the broadcast, the High-level broadcast can decide whether to cut off the broadcast.
5. Experimental phenomenon: in the broadcast sent by this method, in the code registration method, the broadcast order is received: indicating the priority, code
Code Demonstration:

Next we will show you how to send an ordered broadcast and transmit data between broadcasts through Intent. Because we have already mentioned the permission block, we will not describe it here, the sendOrderedBroadcast (intent, receiverPermission) method is used to send an ordered broadcast. The second parameter is set to null. Here we use xml to register the broadcast.

1) define Broadcast

Public class MyBroadcast2 extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {System. out. println ("MyBroadcast2 started! "); // Receives the parameter System in the Intent passed by sendOrderedBroadcast. out. println (intent. getStringExtra ("test"); // Add another parameter Bundle bundle = new Bundle (); bundle. putString ("test2", "data I stored from MyBroadcast2"); // encapsulate it as a Bundle object, so that the next broadcast receives setResultExtras (bundle );}}
Public class MyBroadcast1 extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {System. out. println ("MyBroadcast started! "); // Receives the parameter System in the Intent passed by sendOrderedBroadcast. out. println (intent. getStringExtra ("test"); // get another data Bundle bundle = getResultExtras (true) carried in the previous broadcast; System. out. println (bundle. getString ("test2 "));}}
2) Declare broadcast in AndroidManifest. xml:

        
             
                              
          
         
             
                              
  
 
In the broadcast stated above, MyBroadcast2 has a higher priority than Mybroadcast1!

3) Send ordered Broadcast

Intent intent = new Intent ("com. xin. action. broadcast"); intent. putExtra ("test", "I am the data sent by sendOrderedBroadcast! "); SendOrderedBroadcast (intent, null );
Test results:



Because the priority of Mybroadcast2 (1000) is higher than that of Mybroadcast1 (900), after the broadcast is sent through sendOrderedBroadcast, it is first received by mybroadcast2, then, in Mybroadcast2, another parameters are set through setResultExtras to be uploaded to Mybroadcast1, and Mybroadcast1 receives the broadcast, and getResultExtras (true) receives the data carried from mybroadcast2, so the above result is displayed! <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel/kernel + c/kernel + cve-vcd4kpha + kernel/XqNK1w/kernel/zT68bVzai547KltcTH + kernel/kernel + LHwo7o8L3A + records/records + 16Ky4bnjsqUtLT6908rVsru1vbnjsqU8L3A + records/records = "http://www.2cto.com/uploadfile/Collfiles/20140823/2014082309213077.jpg" alt = "\">

We register the broadcast: RegisterActivity in the registered broadcast Activity, and cancel the registration of the broadcast unregisterBr in the onPause method of its life cycle.

// Define broadcast BroadcastReceiver receiver ER = new BroadcastReceiver () {@ Overridepublic void onReceive (Context context, Intent intent) {String action = intent. getAction (); int count = intent. getIntExtra ("count", 0); System. out. println ("action =" + action + ", count =" + count) ;}}; // register broadcast @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. register); IntentFilter Filter = new IntentFilter (); // Add broadcast Actionfilter. addAction ("com. xin. action. broadcast "); filter. addAction ("com. xin. action. sticky. broadcast "); registerReceiver (filter);} // cancel registration broadcast @ Overrideprotected void onPause () {super. onPause (); System. out. println ("RegisterBroadActivity onPause! "); UnregisterReceiver (receiver );}
Send broadcast in MainActivity:

// Define a variable to count the number of times of clicking to send a sticky broadcast, and then test whether the receipt of the sticky broadcast is the last private int count; @ Overridepublic void onClick (View v) {Intent intent = null; switch (v. getId () {case R. id. btn_send1: // send broadcast sendBroadcastintent = new Intent ("com. xin. action. broadcast "); sendBroadcast (intent); break; case R. id. btn_send2: // send a stickybroadcastcount ++; intent = new Intent ("com. xin. action. sticky. broadcast "); intent. putExtra ("count", count); sendSticky Broadcast (intent); break; case R. id. register: // start the register broadcast page intent = new Intent (MainActivity. this, RegisterBroadActivity. class); startActivity (intent); break ;}@ Overrideprotected void onResume () {super. onResume (); count = 0; System. out. println ("MainActivity onResume! ");}
Note: To send sticky broadcasts, you must add the permission to send sticky broadcasts to AndroidManifest. xml. Otherwise, an error is returned:

 
Test and conclusion:

When we click send sendBroadcast three times -- click Register, the console does not output the result

When we click send sendStickyBroadcast four times -- click Register, the console outputs the result: action = com. xin. action. sticky. broadcast, count = 4

This is the difference between normal broadcast and viscous broadcast.
The broadcast sent by sendBroadcast. If no broadcast is registered, the advertisement cannot be received. When the broadcast is registered again, the advertisement cannot be received.
The broadcast sent by sendStickyBroadcast. If no broadcast is registered, the advertisement cannot be received at this time. After the broadcast is registered again, the advertisement will be received, in addition, it will accept the last broadcast sent by sendStickyBroadcast. Therefore, in the output result above, click send stickybroadcast four times, and count becomes 4. After the broadcast is re-registered, the console outputs the result count = 4;
The last Intent sent by sendStickyBroadcast will be retained. The next time the Recevier is active, it will be accepted.

When we need to remove the stickbroadcast, call removeStickyBroadcast (intent); To clear the stickybroadcast.

There is also a way to send the broadcast: sendStickyOrderedBroadcast (), test the broadcast sent from this method, in the code registration method, the order of received broadcasts is: indicates the priority, the code is registered, and there is no priority. If there is no priority, the code registration is received first.

The preceding describes several broadcast operations:

Send broadcast: sendBroadcast (Intent intent), sendBroadcast (Intent intent, String receiverPermission );

Send ordered broadcast: sendOrderedBroadcast (Intent intent, String receiverPermission );

Send stickybroadcast (Intent intent );

Another method is sendStickyOrderedBroadcast)


In Broadcast Operations of Android, we should also know:

1. For ordered broadcast or unordered broadcast, the broadcast receiver is running in the main thread by default (main thread, that is, UI thread ). You can specify the thread of the broadcast receiver to run by using the last parameter in the registerReceiver (receiver er, filter, broadcastPermission, schedsion) method in the program. You can also set it in the Manifest. xml file (set android: process in the Intent-filter tag ).

2. If we register registerBroadcast for ten times in the Code, the broadcast will receive ten times when it is sent, and only one time is required to cancel the broadcast!

3. Each time the broadcast arrives, the BroadcastReceiver object is re-created and the onReceive () method is called. After execution, the object is destroyed. when the onReceive () method is not completed within 10 seconds, Android considers the program to be unresponsive. therefore, you cannot perform some time-consuming operations in BroadcastReceiver. the ANR (Application NoResponse) dialog box is displayed on the other side. To complete a time-consuming task, you should send Intent to the Service, it is done by the Service. subthreads cannot be used here, because the life cycle of BroadcastReceiver is very short, and the subthread may end before it ends. once BroadcastReceiver ends, the process where BroadcastReceiver is located is easily killed first when the system requires memory because it is a blank process (process without any active components ). if its host process is killed, the working sub-thread is also killed. therefore, it is unreliable to use sub-threads.

4. Time-consuming operations should be performed by starting the service through broadcast

BroadcastReceiver receiver=new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {Intent intent=new Intent(context,TestService.class);startService(intent);}};

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.