Android programming four components of BroadcastReceiver of broadcast receiver usage instance

  • 2020-12-10 00:52:48
  • OfStack

This article illustrates the use of BroadcastReceiver(broadcast receiver) for the four components of Android programming. To share for your reference, the details are as follows:

Here's how to create a broadcast, how to send an unordered broadcast and an ordered broadcast, and how to listen for text messages and listen for outgoing calls (when we text and make a call, the system sends a broadcast, and we can intercept this broadcast to listen for text messages and listen for outgoing calls).

Define broadcast receiver

1. Define class inheritance BroadcastReceiver and override onReceive method
2. The onReceive method executes when a matching broadcast is received
3. Declaration in the manifest file < receiver > , which needs to be configured < intent-filter > Specifies the action and type to receive the broadcast
BroadcastReceiver can be declared in code as well as in the manifest file to register Receiver using the registerReceiver method

Send broadcast

A disorderly radio

1. Send using sendBroadcast method
2. Received by all broadcast receivers, unordered and non-interruptible
3. Receiver permission can be set when broadcasting, and can be received only if the receiver has permission
4. Recipient's < receiver > You can also set sender permissions to receive only broadcasts that have permissions applied

Orderly broadcast

1. Send using sendOrderedBroadcast method
2. The receiver can be at < intent-filter > android:priority defines the priority. The higher the number, the higher the priority
3. Received by each broadcast receiver one by one, data can be interrupted or added during the process


abortBroadcast() // Interrupt radio 
getResultExtras(true).putString("data", " The new data "); // Add data 
getResultExtras(true).getString("data") // Receive data 

Monitor SMS reception

1.Android system will send an orderly broadcast when it receives a text message. If we define a receiver to receive this broadcast, we can get the content of the text message and also intercept the text message
2. Define receive broadcast radio receiver android. provider. Telephony. SMS_RECEIVED
3. Call getExtras() of Intent inside the onReceive method to get the pdus field and get 1 Object[], where each element is 1 byte[]
4. Create the SmsMessage object with the createFromPdu method of the SmsMessage class
5. The sender number, message content, sending time and other information can be obtained from the object SmsMessage
6. Need to receive SMS permission:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

7. The message received in Android system is an orderly notification. If we need to intercept spam messages, we can configure a higher priority to judge whether abortBroadcast() is acceptable after receiving the message.

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="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <receiver android:name=".SmsReceiver">
      <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter>
    </receiver>
  </application>
  <uses-sdk android:minSdkVersion="8" />
  <!--  Access to SMS messages  -->
  <uses-permission android:name="android.permission.RECEIVE_SMS"/>
</manifest>

Listen to 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) {
    Object[] pdus = (Object[]) intent.getExtras().get("pdus");
    for (Object pdu : pdus) {
      // create 1 A short message 
      SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
      // Gets the sending cell phone number 
      String address = sms.getOriginatingAddress();
      // Get the content of the message 
      String body = sms.getMessageBody();
      // The time to get the message 
      String time = 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 cell phone reception 
    abortBroadcast();
  }
}

Monitor outgoing calls

1. Define radio receiver receive android. intent. action. NEW_OUTGOING_CALL
2. You need permission

<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 your phone number 
  String num = getResultData();
  // ...  Check whether it is local 
  // Operate on the obtained phone number 
  setResultData("17951" + num);
}

The life cycle

1. The life cycle of the broadcast receiver is very short, created when the broadcast is received, and destroyed after the onReceive() method finishes
2. Do not do any time-consuming work on the broadcast receiver or the Application No Response error dialog will pop up
3. It is also best not to create a child thread in the broadcast receiver to do time-consuming work, because after the broadcast receiver is destroyed, the process becomes empty and can be easily killed by the system
4. Long, time-consuming work is best done in the service

I hope this article is helpful for Android programming.


Related articles: