首先我们要配置一些清单文件
<receiver android:name="com.example.smslinser.MyReceiver" >
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
过滤器代表短信过滤
然后还要配置优先级,这个范围是从-1000到1000,我们要做拦截功能必须保证我们写的短信接受者,在系统的短信接受者前接收到
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
package com.example.smslinser; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. Bundle bundle = intent.getExtras(); //得到接收的短信,这么设计的目的是为了发送很长的时候能够接收 Object[] object = (Object[]) bundle.get("pdus"); for (int i = 0; i < object.length; i++) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])object[i]); //得到发信人号码 String address = smsMessage.getOriginatingAddress(); //得到信息内容 String body = smsMessage.getMessageBody(); if(address.equals("138")){ //不让其他的广播接收者接收 abortBroadcast(); } System.out.println("address:"+address+"body:"+body); } } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.smslinser" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" 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.example.smslinser.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.example.smslinser.MyReceiver" > <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> </application> </manifest>