Android使用广播接收器(broadcastReceiver)实现短信窃听和拦截功能

1、AndroidManifest.xml清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.t20.smsReceiver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />
    <!-- 获取短信权限 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.t20.smsReceiver.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="com.t20.receiver.SmsReceiver">
           <intent-filter android:priority="1000" >
           <!-- 有序广播设置优先级:priority表示优先级(0-1000),默认是500 ,1000的优先级最高-->
               <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
           </intent-filter>
        </receiver>
    </application>

</manifest>

2、SmsReceiver.java

package com.t20.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		//1、接收短信协议
		Bundle bundle= intent.getExtras(); //Bundle表示MAP套装(键值对)
		//2、通过Bundle取值
		Object[] objs= (Object[]) bundle.get("pdus");
		for (Object obj : objs) {
			//3、获取短信对象
			SmsMessage sms=SmsMessage.createFromPdu((byte[])obj);
			System.out.println("短信联系人:"+sms.getOriginatingAddress());
			System.out.println("短信内容:"+sms.getDisplayMessageBody());
			//4、短信拦截(收到短信时,系统会发一个有序广播,默认优先级是500,我们可以设置短信窃听器的广播优先级为1000)
			if(sms.getOriginatingAddress().equals("110")){
				abortBroadcast();//终止广播
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq15577969/article/details/80760583