Broadcastreceiver (broadcast receiver) usages of four components of Android programming _android

Source: Internet
Author: User

This example describes the Broadcastreceiver (broadcast receiver) usage of the four components of Android programming. Share to everyone for your reference, specific as follows:

Here's how to create a broadcast, send a disorderly broadcast and ordered broadcast, listen to SMS and listen for outgoing calls (when we send text messages and make a phone call, the system sends a broadcast and we can intercept the radio for listening for text messages and listening for outgoing calls).

Define broadcast receivers

1. Define class inheritance Broadcastreceiver, overriding onreceive methods
2. The OnReceive method is executed when a matching broadcast is received
3. Declaration of <RECEIVER> in the manifest file, where you need to configure <intent-filter> specify the actions and types of the receive broadcast
4.BroadcastReceiver In addition to the declaration in the manifest file, can also be declared in the code, using the Registerreceiver method to register receiver

Send broadcast

Disorderly broadcast

1. Use the Sendbroadcast method to send
2. Received by all broadcast receivers, disorderly, not interrupted
3. You can set receiver permissions when broadcasting, only when the receiver has permission to receive
4. Receiver's <receiver> can also set the sender's permission, only receives the broadcast which has the permission application

Ordered broadcast

1. Use the Sendorderedbroadcast method to send
2. The receiver can define the priority of android:priority in <intent-filter>, the higher the number, the greater the priority.
3. Be received by each broadcast receiver, midway can interrupt or add data

Abortbroadcast ()///Interrupt Broadcast
Getresultextras (true). Putstring ("Data", "add");///Adding Data
Getresultextras (TRUE). GetString ("Data")//Receive data

Listening for SMS Reception

The 1.Android system sends a sequential broadcast when it receives a message, and if we define a recipient to receive the broadcast, we can get the message or intercept the message.
2. Define broadcast receivers to receive broadcast Android.provider.Telephony.SMS_RECEIVED
3. Call Intent's Getextras () inside the OnReceive method to get PDUs field, get a object[], where each element is a byte[]
4. Creating Smsmessage objects through the Createfrompdu method of the Smsmessage class
5. From the Smsmessage object can get the sender number, SMS content, sending time and other information
6. Need to receive SMS permission:

Copy Code code as follows:
<uses-permission android:name= "Android.permission.RECEIVE_SMS"/>

7.Android system received SMS notification is an orderly notification, we need to intercept spam message, you can configure a higher priority, received information to determine whether Abortbroadcast ()

Example:

Listing

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Cn.test "android:versioncode=" 1 "android:versionname=" 1.0 "> <application android:icon=" @drawable/icon "android:label=" @string/app_name "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action android:name=" a Ndroid.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </int ent-filter> </activity> <receiver android:name= ". Smsreceiver "> <intent-filter android:priority=" 999 "> <action android:name=" Android.provider.Tele Phony.sms_received "/> </intent-filter> </receiver> </application> <uses-sdk Android : minsdkversion= "8"/> <!--receive SMS privileges--> <uses-permission android:name= "Android.permission.RECEIVE_SMS"/ > </Manifest>

 

Listening for SMS broadcasts:

Package cn.test;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.telephony.SmsMessage;
public class Smsreceiver extends Broadcastreceiver {public
  void OnReceive (context context, Intent Intent) {
    OBJ Ect[] PDUs = (object[]) Intent.getextras (). Get ("PDUs");
    for (Object pdu:pdus) {
      ///Create a SMS
      smsmessage SMS = SMSMESSAGE.CREATEFROMPDU ((byte[)) PDU)
      ; Get send mobile number
      String address = sms.getoriginatingaddress ();
      Gets the content of the text
      String BODY = Sms.getmessagebody ();
      Get SMS time
      String = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (New Date (Sms.gettimestampmillis ());
      System.out.println (time);
      SYSTEM.OUT.PRINTLN (address);
      System.out.println (body);
    Interrupt phone receive Operation
    Abortbroadcast ();
  }


Monitor the call.

1. Define broadcast receiver receive Android.intent.action.NEW_OUTGOING_CALL
2. Need permission

Copy Code code as follows:
<uses-permission android:name= "Android.permission.PROCESS_OUTGOING_CALLS"/>

3. Use the Getresultdata () and Setresultdata () methods in the OnReceive method to get and set the phone number

public void OnReceive (context context, Intent Intent) {
  //Get to cell phone number
  String num = Getresultdata ();
  // ... Query whether to
  operate locally//on the phone number you get
  setresultdata ("17951" + num);
}

Life cycle

1. The life cycle of the broadcast receiver is very brief, created when the broadcast is received, and destroyed after the OnReceive () method is completed
2. Do not do some time-consuming work in the broadcast receiver, otherwise pop-up application No Response error dialog box
3. It is also best not to create child threads in broadcast receivers to do time-consuming work, since the broadcast receiver is destroyed and the process becomes an empty process that can easily be killed by the system.
4. A long and time-consuming work is best done in the service

I hope this article will help you with the Android program.

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.