Android: Intercepting system Broadcastreceiver

Source: Internet
Author: User
Tags filter final format message ip number

Broadcasts in the system

In the Android system, a lot of action output is built in, and the corresponding broadcast are released when the action is triggered. In general, looking at the Android API documentation, a description of intent is available to find the broadcast for the action, but the list is not exhaustive and it is best to download the Android source code, View the broadcast that you want to intercept by viewing the source code.

Here are some common broadcasts:

    • Android.intent.action.TIME_SET: The system time has been modified.
    • Android.intent.action.DATE_CHANGED: The system date was modified.
    • Android.intent.action.BOOT_COMPLETED: System boot complete.
    • Android.intent.action.BATTERY_CHANGED: Changes in the electrical capacity of the equipment.
    • Android.intent.action.BATTERY_LOW: Low equipment charge.
    • Android.intent.action.ACTION_POWER_CONNECTED: Device connection power.
    • Android.intent.action.ACTION_POWER_DISCONNECTED: The power is disconnected from the device.
    • Android.provider.Telephony.SMS_RECEIVED: The system received a text message.
    • Android.intent.action.NEW_OUTGOING_CALL: Dial the phone.

Here are two examples of how to intercept and process a system broadcast under Android.

Intercept SMS by keyword

Some of the actions listed above will be released broadcast, can be found, when the system received a message, will release a "Android.provider.Telephony.SMS_RECEIVED" broadcast, has been introduced before, The general system broadcast is ordered broadcast, if not by the high priority Broadcastreceiver stop delivery, will be in order of priority to pass down.

In this example, by listening to receive SMS broadcast, when its content has a black list of keywords, then prevent broadcast continue to spread, and use toast prompts, otherwise normal prompts SMS message.

I learned from the previous blog that the intent parameter of the OnReceive method contains the parameters of the broadcast, and for SMS messages, you need to get an array of key "PDUs", take out each item in the array, and each of its items represents a byte[] format message. You need to use the Smsmessage class to parse SMS content.

Of course, the interception of SMS broadcast violated privacy, need to register the right to receive text messages:

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

The following is a direct demonstration of the source code, the key note has been written clearly, here is no longer tired:

Messagebroadcast.java:

 1 package Cn.bgxt.Broadcastdemo.MessageWarn;
 2 3 Import Java.text.SimpleDateFormat;
 4 Import java.util.Date;
 5 Import Android.content.BroadcastReceiver;
 6 Import Android.content.Context;
 7 Import android.content.Intent;
 8 Import Android.os.Bundle;
9 Import Android.telephony.SmsMessage;
Import Android.widget.Toast; One of the public class Messagebroadcast extends Broadcastreceiver {13////On the simulator, sending SMS via DDMS will generate garbled text, so use pinyin instead of 14//on the real machine does not exist
Garbled problem of the final string[] Blackkeyword = new string[] {"Baoxian", "Chuxiao", "Jiangjia"}; @Override public void OnReceive (context context, Intent Intent) {20//Determine if the currently received broadcast is receiving a text message             Action if (Intent.getaction () equals ("Android.provider.Telephony.SMS_RECEIVED")) {23
StringBuilder sb = new StringBuilder ();
24//Get the data passed by broadcast Bundle Bundle = Intent.getextras ();              if (bundle!= null) {27   Object[] PDUs = (object[]) bundle.get ("PDUs"); for (Object P:pdus) {byte[] pud = (byte[]) p; 30//Declare an S
Msmessage, byte[] array for parsing SMS = smsmessage message = SMSMESSAGE.CREATEFROMPDU (PUD);
Boolean flag = false; A for (String Str:blackkeyword) {message.getmessagebody (). Contains (                             STR)) {35///Discovery blacklist keyword, then mark as true flag = true; 37
Break The IF (flag) {Sb.app
End ("Sender: N");
Sb.append (Message.getoriginatingaddress ());
Sb.append ("N Send time: n");
Date = new Date (Message.gettimestampmillis ());     SimpleDateFormat format = new SimpleDateFormat (46                            "Yyyy-mm-dd HH:mm:ss");
Sb.append (Format.format (date));
Sb.append ("N Short Message content: N");
Sb.append (Message.getmessagebody ()); Toast.maketext (Context, sb.tostring (), Toast.length_shor
T). Show ();
53//If there is a blacklist keyword content, stop broadcast spread abortbroadcast (); 55} 56 57} 58} 59} 60 61} 62 63}

Configure receiver in Androidmanifest.xml.

1         <receiver android:name= "Cn.bgxt.Broadcastdemo.MessageWarn.MessageBroadcast" >
2             <!--setting priority , SMS priority is 0, greater than 0 can-->
3             <intent-filter android:priority= ">
4                 <action android:name=" Android.provider.Telephony.SMS_RECEIVED "/>
5             </intent-filter>            
6         </receiver>

Effect display, first send a message containing the keyword in the blacklist, and then send a normal text message.

IP dialing

Looking at an example of IP dialing, in Android, if you trigger the call action, you will release a "Android.intent.action.NEW_OUTGOING_CALL" broadcast, only to intercept it , and then add the IP prefix, the processed number to the data to pass to the next receiver.

To handle broadcast that receive calls, you need to add permissions to Android:

1 <uses-permission android:name= "Android.permission.PROCESS_OUTGOING_CALLS"/>

The following directly on the code, notes written very clearly, here is no longer tired.

Ipcallphone.java:

 1 package cn.bgxt.Broadcastdemo.IpCall;
 2 
 3 import android.content.BroadcastReceiver;
 4 Import Android.content.Context;
 5 import android.content.Intent;
 6 
 7 public class Ipcallphone extends Broadcastreceiver {
 8     private final String starts= "17951";
 9     @Override
public     void onreceive (context, Intent Intent) {One         //Get the number
currently dialed A         String number=getresultdata ();
/         /This number is not prefixed with IP dialing         (!number.startswith (starts)) {             //Set the number             with IP number added String Newnumber=starts+number;             Add the new number to the return result data, which is used to pass to receiver             setresultdata (newnumber);
}
21}

Androidmanifest.xml Configuration receiver:

1         <receiver android:name= "Cn.bgxt.Broadcastdemo.IpCall.IpCallPhone" >
2             <intent-filter android:priority= >
3                 <action android:name= "Android.intent.action.NEW_OUTGOING_CALL"/>
4             </intent-filter>
5         </receiver>

Effect Display:

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.