Android Basic Note (ix)-broadcast

Source: Internet
Author: User
Tags get ip

    • The concept of broadcasting
    • The life cycle of the broadcast
    • Case-Listen to SMS and parse SMS content
    • Case-intercept outgoing calls and set the area code
    • Case-SD Card Status monitoring
    • Introduce some of the frequently used broadcasts
    • Send yourself definition Broadcast
    • Ordered broadcast and unordered broadcasts

Leave!!

The concept of broadcasting

In Android. Broadcast is a widely used mechanism for transmitting information between applications. BroadcastReceiverIt is a class of components that are filtered to receive and respond to the broadcast sent out.

The broadcast receiver ( BroadcastReceiver ) is used to receive broadcast intent, and the broadcast intent is sent by call sendBroadcast/sendOrderedBroadcast . Typically a broadcast intent can be received by multiple broadcast receivers subscribed to this intent.

Type of broadcast:
unordered Broadcast (Normal broadcasts). Similar to the daily use of WiFi, by a broadcaster to send a signal. Can have very many receivers at the same time, and the signal can not be interrupted and tampered with.
Orderly Broadcast (Ordered broadcasts), can have finally receiver. And there is the priority of signal reception;
To define the broadcast recipient:
① defines a class, inherits BroadcastReceiver , and overrides onReceive(Context context, Intent intent) methods to handle the event of a broadcast arrival.
② Register the broadcast recipient.

There are two ways, one is static: The tag is implemented in the file, and the other AndroidManifest.xml <receiver> is dynamic: Use the method to dynamically register the Context.registerReceiver() broadcast receiver.

Note: register your broadcast receiver in the Activity.onResume() method, and counter-register your broadcast receiver in Activity.onPause() .

The broadcast recipient of this booklet. are declared in the manifest file, and the code register is explained in the next article;

The life cycle of the broadcast

The broadcast receiver is also executed in the main thread, so there is no time-consuming operation within the broadcast receiver's OnReceive method. Need to be done in a sub-thread.

onReceiveLife cycle is very short, it is possible for the broadcast receiver to end. The child thread is not finished yet. At this point the broadcast receiver process is very likely to be killed, this way the thread will be a problem, so the time-consuming operation is best put into service services.

Precautions:
The
life cycle of the ① broadcast receiver is very short, created when the broadcast is received, and destroyed after the OnReceive () method finishes.
② Broadcast recipients do not do some time-consuming work, or the Application No Response error dialog box will pop up.

③ It is best not to create sub-threads in the broadcast receiver to do time-consuming work, since the broadcast recipient is destroyed after the process becomes an empty process. Very easy to be killed by the system.
Case-Listen to SMS and parse SMS content

* * Note: After the **4.0 version number for security reasons, the application must have an interface and be executed once. Program talent to 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 frequently used APIs;

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

 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. AndroidManifest.xmlimplement tags in documents <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 in the manifest file declaration <receiver> , do not use the wrong label, if written <activity> . System execution will not error, but will not receive broadcast events.

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

Case-intercept outgoing calls and set the area code

is also a very easy case, according to the above steps to create and declare, join the filter can be, 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 a filter that needs to be added to the outbound call broadcast--    <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 to try:

We dialed 110 and became 010110 after our own definition of the broadcast receiver. Indicates that we have successfully changed the data in the outgoing call broadcast. So let's take a look getResultData() and setResultData(String) . One is to get the data in the broadcast. One is to change the data in the broadcast;

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

Case-SD Card Status monitoring

The required filters in the manifest file are as follows, in order to monitor the status of the unloaded SD card. The type of scheme must be specified 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 refers to the object that we are able to onReceiver() pass through to our intent intent. Get the action that triggered the broadcast.

Introduce some of the frequently used broadcasts
Start your own active broadcast

ANDROID3.0 once did not need to add permission, the 3.0 version number is added after the security, assuming that the application has not been opened, is not able 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. Intercept action:

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

Sending custom broadcasts is also very easy, based on Google's API discovery to use the sendBroadcast(intent) method to send an intent as a broadcast.

In addition We know that Intent an object can set an intent (broadcast) action Action . This kind of speech only wants to broadcast the receiver to set up the concern action, will be able to 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). will be able 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 received after the broadcast. The processing of the code.

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

In the beginning we know that there are disordered broadcasts and ordered broadcasts, and ordered broadcasts have already described how to create and use them, so how does an unordered broadcast be created and used? And what is the difference between them?

Shuffle broadcast
Can not be intercepted
Orderly broadcast
① is sent in accordance with a certain priority, can be configured in the <intent-filter android:priority="1000"> priority level, the priority range is ( -1000,1000)
② can be intercepted, data can be changed.

Follow the next step by using an orderly broadcast to see how it works.

It is necessary to say in advance that in an orderly broadcast, we are able to use broadcastReceiver.setResult(int code, String data, Bundle extras) methods to alter the data in the broadcast and to use broadcastReceiver.abortBroadcast() methods to terminate the broadcast.

① First , create 发送有序广播 project and send an ordered broadcast. An ordered broadcast has a lot of parameters, and the gaze is given in the code.

The action that we give to the broadcast is what com.bzh.sendorder this means. 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;//listener for orderly broadcasts. Will receive the outgoing broadcast at the end of theBroadcastreceiver Resultreceiver =NewFinalreceiver (); Handler Scheduler =NULL;//Broadcast send code    intInitialcode = $;//broadcast content that can be obtained using the Getresultdataa () methodString 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;

The same is inherited BroadcastReceiver but does not need to be declared in the manifest file.

The following is the code for 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 有序广播接收者 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);//change of data carriedResultextras.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 + ", carrying data: " + 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:

To be able to see clearly. The results are in the order in which our code is written.

Combine work and interview

Please describe the broadcast?
Broadcasting is an event of the Android system, which he distributes through the broadcast mechanism, and the system has achieved a very great number of broadcast receivers.

Like: Low battery, phone restart, receive SMS, make Phone call, SD card mount, an APK successfully installed ..., the system will be broadcast to these events distributed.

After the broadcast is distributed, if someone wants to receive the broadcast, it needs to use the broadcast receiver.

Sticky broadcast?
Sticky: Sticky development is rarely used. But the interview is likely to ask:
Sendstickybroadcast (Intent)//The Haunting broadcast (sticky broadcast)
Sticky broadcast, will wait until the intent specified event has been processed before it disappears.
The life cycle of a broadcast recipient is shorter. Generally, the broadcast will end around 10s, but some broadcast events are more time-consuming. For example, WiFi status changes.
WiFi settings: Send WiFi status change broadcast, the system is implemented through Sendstickybroadcast, because the access to the WiFi status change is a very time-consuming operation (get the SSID of the phone, and will get IP address and so a series of operations), Let's say it's a normal way to send a broadcast, not waiting for WiFi status to get finished. The radio is over.

Android Basic Note (ix)-broadcast

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.