Android Broadcast Receiver learning _

A broadcast

1. Standard Broadcasting and orderly broadcast

Standard broadcast: an asynchronous message is issued, all receivers simultaneously receive. But it can not be cut off

Ordered Broadcast: synchronous, that only one broadcast receiver receives. You can truncate the message.

 

2. Radio Registration

Registration code (dynamic registration), AndroidManifest.xml registered (static registration)

1) dynamic registration

Dynamic registration more flexible, but must be able to receive the broadcast after the program starts.

Step1: a new class inherits class BroadcastReceiver (custom class or internal), and override onReceive method (after a corresponding broadcast receiver receives the broadcast, automatically calls onReceive () method)

Step2: Creating IntentFilter and add action needs to listen to the broadcast value corresponding to

Step4: with registerReceiver () register a listener, and the listener IntentFilter instance as a parameter into two (Context.registerReceiver () method)

Step3: Rewrite where the activity of onDestory () method, unregister listeners onDestory () with unregisterReceiver () (dynamic broadcast receivers must register unregister)

 

Note: If the program requires some users to sensitive operations, permission must be declared in the configuration file

2) static registration

Will be able to receive the broadcast program did not start

 

2. Send custom broadcast

1) transmits a broadcast standard

Intent intent = new Intent ( "com.example.broadcasttest.MY_BROADCAST"); // com.example.broadcasttest.MY_BROADCAST custom broadcast value

sendBroadcast (intent);

 

Tip: can carry some of the data transmitted to the broadcast receiver in intent.

2) Send orderly broadcast

sendOrderedBroadcast(intent,null);

u Set priority:

<intent-filter android:priority=”100”>…

u truncated broadcast

Call abroadBroadcast () in onReceive () method method

 

3. Local Broadcast

Address security issues broadcasting.

 

First () method by which examples of getInstance LocalBroadcastManager.

Register broadcast receiver: LocalBroadcastManager.registerReceiver (localReveiver, intentFilter);

Broadcast transmission: LocalBroadcastManager.sendBroadcast (intent);

Cancel Registration: LocalBroadcastManager.unregisterReceiver (localReceiver);

 

4. Best Practices - function implemented forced offline

1) the use of inheritance improve code reusability

2) register the broadcast receiver in onResume, unregister the onPause. This ensures that only is at the top of the activity in order to receive the broadcast, non-stack activities not receive.

Guess you like

Origin www.cnblogs.com/pomodoro/p/11315187.html