Android two kinds of registration, send broadcast the difference

Source: Internet
Author: User

Preface : The previous article recorded Service the use, this time to record one of the other four components BroadcastReceiver . It mainly introduces the difference between two types of broadcast and registration.

BroadcastReceiverBroadcast receivers are used to receive broadcasts sent by systems or other programs, including their own programs.

I. Registration of Broadcasts

In Android, if we want to receive broadcast information, we must customize our broadcast recipients. To write a class to inherit BroadcastReceiver , and override its onReceive() methods to implement what is required to receive a particular broadcast.

This is a custom broadcast recipient:

public class MyBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //在这里可以写相应的逻辑来实现一些功能 //可以从Intent中获取数据、还可以调用BroadcastReceiver的getResultData()获取数据 } }

We have defined a broadcast receiver. To use it to receive a broadcast, register the broadcast receiver.

There are two ways of registering a broadcast:

(1) dynamic registration in code

The steps are as follows:

    1. Instantiate a custom broadcast recipient
    2. Instantiate the intent filter and set the broadcast type to be filtered (for example, we receive a broadcast sent by the SMS system)
    3. Register a broadcast using the Registerreceiver (Broadcastreceiver, Intentfilter, String, Handler) method of the context

Code:

//new出上边定义好的BroadcastReceiverMyBroadCastReceiver yBroadCastReceiver = new MyBroadCastReceiver();//实例化过滤器并设置要过滤的广播  IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");//注册广播 myContext.registerReceiver(smsBroadCastReceiver,intentFilter, "android.permission.RECEIVE_SMS", null);
(2) static registration in Manifest.xml

Configure the Manifest.xml broadcast recipient directly in the node of the file <application> .

<receiver android:name=".MyBroadCastReceiver">              <!-- android:priority属性是设置此接收者的优先级(从-1000到1000) --> <intent-filter android:priority="20"> <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>

Also configure the <application> permissions that may be used at the same location as the sibling

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
(3) The difference between two types of registered broadcasts
    1. The first is not a resident broadcast, which means that the broadcast follows the program's life cycle.
    2. The second type is resident, which means that when the application is closed, the program is automatically run by the system call if there is a message broadcast.
Two. Send a broadcast

When we need to send a custom broadcast to notify other components in the program of some state, we can use the way to send a broadcast.

There are two different ways to send two kinds of broadcasts:
An mContext.sendBroadcast(Intent) mContext.sendBroadcast(Intent, String) unordered broadcast is passed or sent (the latter adds a permission);
By mContext.sendOrderedBroadcast(Intent, String, BroadCastReceiver, Handler, int, String, Bundle) sending an ordered broadcast.

difference :
Shuffle broadcasts: All receivers receive events, cannot be intercepted, and cannot be modified.
Orderly broadcast: By priority, a level down pass, the receiver can modify the broadcast data, or can terminate the broadcast event.

(1) Use of disordered broadcasting:

Define a button, set its Click event, and send an unordered broadcast.

        new  Intent();        //设置intent的动作为com.example.broadcast,可以任意定义        intent.setAction("com.example.broadcast");        //发送无序广播        sendBroadcast(intent);

Define a broadcast receiver to receive this broadcast event. Determine whether a broadcast is received by the Toast's print

public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"收到广播", Toast.LENGTH_SHORT).show(); }}

Configure the recipient in the Manifest.xml.

<receiver            android:name=".MyReceiver" >            <intent-filter> <!-- 动作设置为发送的广播动作 --> <action android:name="com.example.broadcast"/> </intent-filter></receiver>

The result is: Toast prints out "receive broadcast".

(2) Use of orderly broadcasting

Unlike out-of-order broadcasts, it is mContext.sendOrderedBroadcast(Intent, String, BroadCastReceiver, Handler, int, String, Bundle) possible to modify or terminate a broadcast before a recipient with a lower priority can get a broadcast by setting a priority with each recipient.

Define a button, set its Click event, and send an ordered broadcast.

        new  Intent();        //设置intent的动作为com.example.broadcast,可以任意定义        intent.setAction("com.example.broadcast");        //发送无序广播        //第一个参数:intent //第二个参数:String类型的接收者权限 //第三个参数:BroadcastReceiver 指定的接收者 //第四个参数:Handler scheduler //第五个参数:int 此次广播的标记 //第六个参数:String 初始数据 //第七个参数:Bundle 往Intent中添加的额外数据 sendOrderedBroadcast(intent, null, null, null, "这是初始数据", );

The

defines multiple broadcast receivers to receive this broadcast event. Determine whether a broadcast

is received by the Toast's print

public class myreceiver1 extends broadcastreceiver {public myreceiver1 () {}  @Override public void  Onreceive//get the data in the broadcast (that is, get " This is the initial data "string") string message = Getresultdata (); Toast.maketext (context, message, Toast.length_short). Show (); //Modify Data Setresultdata ( "This is the modified data");}}      
public class myreceiver2 extends broadcastreceiver {public myreceiver2 () {}  @Override public void  Onreceive//Stop broadcast Abortbroadcast ();}          
public class MyReceiver3 extends BroadcastReceiver { public MyReceiver3() { } @Override public void onReceive(Context context, Intent intent) { String message = getResultData(); Toast.makeText(context ,message ,Toast.LENGTH_SHORT).show(); }}

Configure the recipient in the Manifest.xml. and set the priority level: Myreceiver1>myreceiver2>myreceiver3.

<!--priority is equal, the priority of receiver written in the front is greater than the back--<ReceiverAndroid:name=". MyReceiver1 "><!--define the priority of the broadcast--<Intent-filterandroid:priority="+" ><!--action set to send a broadcast action--<ActionAndroid:name="Com.example.broadcast"/></Intent-filter></Receiver><ReceiverAndroid:name=". MyReceiver2 "><!--define the priority of the broadcast--<Intent-filterandroid:priority="0" ><!--action set to send a broadcast action--<ActionAndroid:name="Com.example.broadcast"/></intent-filter></ receiver><receiver android:name=. MyReceiver3 "> <!--define broadcast priority--< intent-filter android:priority= "-1000 "> <!--action set to send broadcast action--< Action android:name= "com.example.broadcast"/> </intent-filter></ Receiver>               

Run Result: MyReceiver1 get broadcast data after printing "This is the initial data", MyReceiver2 received broadcast data printing "This is modified data", MyReceiver3 not print.

Android two kinds of registration, send broadcast the difference

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.