不废话说重点:
AndroidManifest.xml文件代码如下:
<uses-permission android:name="android.permission.RECEIVE_SMS"/> <!-- 拦截短信(就是接受短些的权限) -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <!-- 开机启动完成后就开始接收(可选权限) -->
<receiver android:name="com.demo.artshell.broadcastreceiverdemo.InterceptReceiver"> <!--这里没有设置android:enable和android:exported属性,参考官方文档-->
<!--这里的优先级为1000,假定你手机中没有安装其他第三方短信拦截软件,如360等,否则其他第三方软件拦截权限过高导致你都应用程序拦截不到短信-->
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/> <!--这里是写死的,参见官方文档-->
</intent-filter>
</receiver>
这里不需要Activity代码,只需要一个BroadcastReceiver子类,源码如下:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class InterceptReceiver extends BroadcastReceiver {
public static final String TAG = "InterceptReceiver";
public static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public InterceptReceiver() {}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"---------------InterceptReceiver onReceive()----------------");
if (ACTION_SMS_RECEIVED.equals(intent.getAction())) {
Bundle carryContent = intent.getExtras();
if (carryContent != null) {
StringBuilder sb = new StringBuilder();
// 通过pdus获取接收到的所有短信息,获取短信内容
Object[] pdus = (Object[]) carryContent.get("pdus");
// 构建短信对象数组
SmsMessage[] mges = new SmsMessage[pdus.length];
for (int i = 0, len = pdus.length; i < len; i++) {
// 获取单条短信内容,以pdu格式存,并生成短信对象
mges[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage mge : mges) {
sb.append("短信来自:" ).append(mge.getDisplayOriginatingAddress()).append("\n")
.append("短信内容:").append(mge.getMessageBody()).append("\n");
Date sendDate = new Date(mge.getTimestampMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sb.append("短信发送时间:").append(format.format(sendDate));
}
Log.i(TAG,sb.toString()); // 打印日志记录
Toast.makeText(context,sb.toString(),Toast.LENGTH_LONG).show();
this.abortBroadcast(); // 不再往下传播
}
}
}
}
接下来通过真机调试:拨打1008611观察移动的回执短信是否被拦截,本程序在 SDK 4.0.3 (华为手机)上测试通过,其他SDK版本没有测试过!
第二种拦截方式,参考链接