Android Basic Note (ix)-broadcast

Source: Internet
Author: User

    • The concept of broadcasting
    • Case-Listen to SMS and parse SMS content
    • Case-intercept outgoing calls and set the area code
    • Case-SD Card Status monitoring
    • Introduction to some popular broadcasts
    • Send Custom Broadcasts
    • Ordered broadcast and unordered broadcasts

Leave!!!

The concept of broadcasting
Type of broadcast:
out-of-order broadcasting (Normal broadcasts), similar to the daily use of WiFi, by a broadcaster to signal, can have many receivers at the same time, and the signal cannot be interrupted and tampered with;
Orderly Broadcast (Ordered broadcasts), can have the final receiver, and there is a signal reception priority;
To define the broadcast recipient:
① defines a class, inherits BroadcastReceiver , and overrides the onReceive(Context context, Intent intent) method to handle the event of a broadcast arrival;
② registers the broadcast recipient. There are two ways, one is static: AndroidManifest.xml implement tags in the file, <receiver> one is dynamic: Use the Context.registerReceiver() method to dynamically register the broadcast receiver;
Note: register your broadcast receiver in the Activity.onResume() method; Reverse register your broadcast receive The person in the Activity.onPause() .

The broadcast recipient of this registration is declared in the manifest file, and the code registration method is explained in the next article;

Case-Listen to SMS and parse SMS content

* * Note: After the **4.0 version for security reasons, the application must have an interface and be run once before the program can receive broadcast events.

Through a small case to explain the use of the broadcast receiver of the procedures and messages broadcast monitoring and operation, and some common APIs;

The first step : Define a class, inherit BroadcastReceiver , and override the onReceive(Context context, Intent intent) method to handle the event of the broadcast arrival;

 Public  class smsreceiver extends broadcastreceiver {    @Override     Public void OnReceive(context context, Intent Intent) {//The following is a fixed notation for getting SMS messagesBundle bundle = Intent.getextras ();//Get the data to the SMSObject[] objects = (object[]) Bundle.get ("PDUs"); for(Object object:objects) {Smsmessage SMS = SMSMESSAGE.CREATEFROMPDU (byte[]) object);//Get the sender of the SMSString originatingaddress = sms.getoriginatingaddress ();//Get the content of the SMSString messagebody = Sms.getmessagebody (); System.out.println (the broadcast recipient receives a text message: ("+ originatingaddress +","+ MessageBody +")"); }    }}

Step two : Register the broadcast receiver. Implement the label in the AndroidManifest.xml file <receiver> ;

<!--permission to receive text messages--<uses-permission android:name="Android.permission.RECEIVE_SMS" /><!--statement Broadcast recipient --<receiver android:name="Com.bzh.sms.SmsReceiver" >   <!--Intent filter to receive SMS broadcast events--   <intent-filter>       <action android:name="Android.provider.Telephony.SMS_RECEIVED" />    </intent-filter></receiver>

It is worth noting that when declared in the manifest file <receiver> , do not use the wrong label, if written <activity> , the system will not error, but will not receive the broadcast event.

In addition, in the onReceiver() method of the Analytic text message is a fixed wording, do not need to remember, use the time to check on the line.

Case-intercept outgoing calls and set the area code

is also a very simple case, follow the above steps to create and declare, add filters on it, here is the main demonstration of the use of several APIs.

<!--access to outgoing calls--<uses-permission android:name="Android.permission.PROCESS_OUTGOING_CALLS" /><!--statement Broadcast recipient --<receiver android:name="Com.bzh.ip.OutCallReceiver" >    <!--receive Outgoing calls the filter that needs to be added--    <intent-filter>        <action android:name="Android.intent.action.NEW_OUTGOING_CALL" >        </Action>    </intent-filter></receiver>

Take a look at the code in the broadcast reception:

publicclass OutCallReceiver extends BroadcastReceiver {    @Override    publicvoidonReceive(Context context, Intent intent) {        String resultData = getResultData();        System.out.println("未加拨区号前:" + resultData);        setResultData("010" + resultData);    }}

Take a look at the test diagram:

We dialed 110 and became 010110 after our custom broadcast receiver, indicating that we have successfully modified the data in the outgoing call broadcast. So let's look at getResultData() and setResultData(String) , one is to get the data in the broadcast, one is to modify the data in the broadcast;

But we also found that setResultData(String) the method of the API has such a sentence only works with broadcasts sent through Context.sendOrderedBroadcast , which indicates that the outgoing call broadcast event, is an orderly broadcast, using Context.sendOrderedBroadcast this method to send, this method is explained in detail in the following case.

Case-SD Card Status monitoring

The filter required in the manifest file is as follows, in order to listen for the status of uninstalling the SD card, you must specify the type of scheme as file:

<receiver android:name="com.bzh.sdcard.SDCardReceiver" >    <intent-filter>        <action android:name="android.intent.action.MEDIA_UNMOUNTED" />        <data android:scheme="file" />    </intent-filter></receiver>

And look at onReceiver() the code in the next

@OverridepublicvoidonReceive(Context context, Intent intent) {    // 获取到触发广播的动作    String action = intent.getAction();    if ("android.intent.action.MEDIA_UNMOUNTED".equals(action)) {        System.out.println("SD卡被卸载了");    }}

The note here is that we can onReceiver() get the action that triggers the broadcast by passing it to our object of intent intent.

Introduction to some popular broadcasts
Auto start broadcast on boot

Android3.0 previously did not need to add permissions, after the 3.0 version added security, if the application has not been opened, is not to receive the system boot completed broadcast.

拦截的动作:android.intent.action.BOOT_COMPLETED需要的权限:android.permission.RECEIVE_BOOT_COMPLETED
Install and uninstall programs for broadcast

Intercept action:

安装: android.intent.action.PACKAGE_ADDED卸载: android.intent.action.PACKAGE_REMOVED

Specify Scheme:package

Interception of incoming SMS broadcasts

(This action was revoked after Android 4.2), but it can still be used to intercept the action:

android.provider.Telephony.SMS_RECEIVED      优先级别设置为最大, 在系统收到短信之前接收短信:priority="1000“
Permissions Required: android.permission.RECEIVE_SMS
Send Custom Broadcasts

Sending a custom broadcast is also simple, according to Google's API Discovery can use the sendBroadcast(intent) method to send an intent as a broadcast.

In addition, we know that Intent the object can set the action of Intention (broadcast), Action so as long as the broadcast receiver set the action of concern, you can receive the broadcast;

Here is a super simple code to send the broadcast;

publicvoidclick(View v) {    new Intent();    intent.setAction("com.bzh.biezhihua");    intent.putExtra("name""别志华");    // Broadcast the given intent to all interested BroadcastReceivers.    sendBroadcast(intent);}

In another project, we created the broadcast receiver and set the intent filter (specifying the action of interest) to get the data;

The following is the configuration of the broadcast recipient in the manifest file.

<receiver android:name="com.bzh.receiverbroadcast.BiezhihuaReceiver" >    <intent-filter>        <!-- 接收感兴趣的广播事件 -->        <action android:name="com.bzh.biezhihua" />    </intent-filter></receiver>

The following is the processing of the code after receiving the broadcast.

@OverridepublicvoidonReceive(Context context, Intent intent) {    // 取出数据    String extra = intent.getStringExtra("name");    System.out.println(extra);}
Ordered broadcast and unordered broadcasts

In the beginning, we knew that there were disordered broadcasts and ordered broadcasts, and ordered broadcasts had already described how to create and use them, so how do you create and use out-of-order broadcasts? And what is the difference between them?

Shuffle broadcast
You can't be intercepted.
Orderly broadcast
① is sent according to a certain priority, can be configured in the priority level, the <intent-filter android:priority="1000"> priority range is ( -1000,1000)
② can be intercepted, data can be modified;

The next step is to use an orderly broadcast to see how it works;

It is necessary to say in advance: In an orderly broadcast, we can use the broadcastReceiver.setResult(int code, String data, Bundle extras) method to modify the broadcast data, you can also use broadcastReceiver.abortBroadcast() methods to terminate the broadcast;

① First , create the 发送有序广播 project, and send an orderly broadcast, ordered broadcast has a lot of parameters, in the code has given the comments;

Where we set the action for the broadcast is com.bzh.sendorder this means that the receiver of the broadcast needs to specify the action and priority in the intent filter;

 Public void Click(View v) {//Broadcast sentIntent Intent =NewIntent (); Intent.setaction ("Com.bzh.sendorder");//Set Action    //Receive the required permission for the broadcast; general fill in nullString receiverpermission =NULL;///orderly broadcast listener, will receive the last broadcast sentBroadcastreceiver Resultreceiver =NewFinalreceiver (); Handler Scheduler =NULL;//Broadcast send code    intInitialcode = $;//broadcast content, you can use the Getresultdataa () method to getString Initialdata ="I'm a radio sender.";//broadcast of data carriedBundle Initialextras =NewBundle (); Initialextras.putstring ("Name","Don't volunteer."); Sendorderedbroadcast (Intent, Receiverpermission, Resultreceiver, Scheduler, Initialcode, Initialdata, Initialextras)    ; System.out.println ("sent an orderly broadcast");}

Perhaps you have noticed that BroadcastReceiver resultReceiver = new FinalReceiver(); it represents the broadcasting receiver for the monitoring of broadcasting, which will receive broadcasts at the end of the broadcast to monitor the changes in the broadcast;

It is also inherited BroadcastReceiver but does not need to be declared in the manifest file;

The following is the code of the Finalreceiver supervisor;

@OverridepublicvoidonReceive(Context context, Intent intent) {    int resultCode = getResultCode();    String resultData = getResultData();    Bundle resultExtras = getResultExtras(true);    String name = resultExtras.getString("name");    System.out.println("我是有序广播最后的监听者-结果码:"",内容:"",携带的数据:" + name);}

② then , create the 有序广播接收者 project and create FirstReceiver and SecondReceiver two broadcast receivers;

The following is the Declaration and code in the manifest file;

<receiver android:name="Com.bzh.receiverorder.FirstReceiver" >   <intent-filter android:priority="+" >        <action android:name="Com.bzh.sendorder" />    </intent-filter></receiver><receiver android:name="Com.bzh.receiverorder.SecondReceiver" >     <intent-filter android:priority="" ">        <action android:name="Com.bzh.sendorder" />    </intent-filter></receiver>

This is the code for the first broadcast receiver:

@Override Public void OnReceive(context context, Intent Intent) {//Get the result code sent by the broadcast    intResultCode = Getresultcode ();//Get the content sent by the broadcastString resultdata = Getresultdata ();//Get the data that is carried on the broadcastBundle Resultextras = Getresultextras (true); String name = Resultextras.getstring ("Name"); System.out.println ("First recipient-result code:"+ ResultCode +", Content:"+ Resultdata +", carry the data:"+ name);//Modify the data you carryResultextras.putstring ("Name","Hu Yuchong");//Continue to disseminate broadcastsSetresult ( -,"I'm the first recipient.", Resultextras);}

This is the code for the second broadcast receiver:

 @Override  public  void  onreceive     (context context, Intent Intent) {int  ResultCode = Getresultcode ();    String resultdata = Getresultdata ();    Bundle Resultextras = Getresultextras (true );    String name = resultextras.getstring ( "name" ); System.out.println ( "second recipient-result code:"  + resultcode +  "content:"     + resultdata +  + name);    Resultextras.putstring ( "name" ,  "I love Everyone" ); Setresult (400 ,  "I am the second recipient" , Resultextras);}  

finally , take a look at the results of the test:

It can be clearly seen that the results are in the order in which our code is written;

Android Basic Note (ix)-broadcast

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.