logo头像
Snippet 博客主题

android 短信监控

android 短信监控

1
2
3
短信监控 方式
1. BroadcastReceiver监听
2. ContentObserver 监听

BroadcastReceiver监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SmsReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage msg = null;
if (null != bundle) {
Object[] smsObj = (Object[]) bundle.get("pdus");
for (Object object : smsObj) {
msg = SmsMessage.createFromPdu((byte[]) object);
Date date = new Date(msg.getTimestampMillis());// 时间
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String receiveTime = format.format(date);

Log.e("receiveTime", "receiveTime:" + receiveTime);
Log.e("fuyanan", "address:" + msg.getOriginatingAddress()
+ " body:" + msg.getDisplayMessageBody() + " time:"
+ msg.getTimestampMillis());
}
}
}
}

ContentObserver 监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class SMSContentObserver extends ContentObserver {
private Context mContext;

public SMSContentObserver(Context mContext,
Handler mHandler) {
super(mHandler); // 所有ContentObserver的派生类都需要调用该构造方法
this.mContext = mContext;
Utils.init(mContext);
}

@Override
public void onChange(boolean selfChange, Uri uri) {
LogUtils.e("onChange(boolean selfChange, Uri uri). selfChange=" + selfChange + ", uri=" + uri);

/**
* 适配某些较旧的设备,可能只会触发onChange(boolean selfChange)方法,没有传回uri参数,
* 此时只能通过"content://sms/inbox"来查询短信
*/
if (uri == null) {
uri = Uri.parse("content://sms/inbox");
}


if (uri.toString().contains("content://sms/raw") || uri.toString().equals("content://sms")) {
return;
}

LogUtils.e("uri == " + uri);

Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String body = cursor.getString(cursor.getColumnIndex("body"));
// 获取短信提供商的手机号
String address = cursor.getString(cursor.getColumnIndex("address"));
LogUtils.d("sms id: " + id + "\n sms body: " + body);
cursor.close();

// +8615313792723
if (address.contains("+86")) {
address = address.substring(3);
}
if (UserManager.getInstance().getNumberMap().containsKey("8888")) {
//all
notifyPlayDone(mContext,address, body,id);
} else if (null != UserManager.getInstance().getNumberMap().get(address)) {
notifyPlayDone(mContext, address, body,id);
}
}
}
else {
Log.e("SMSContentObserver", "error: cursor == null");
}
}
}

问题

  • 广播多次收到监听
1
2
当短信内容长度大于 70 时候,会分条发送
出现 收到 多次广播现象
  • ContentObserver 收到监听
1
2
3
4
5
6
7
8

onChange 会调动两次

mUri===content://sms/raw/20
mUri===content://sms/inbox/20

点击短信 阅读后 数据库会变更为已读
mUri===content://sms

过滤掉 raw表数据变更 和 已读数据变更 处理

1
2
3
if (uri.toString().contains("content://sms/raw") || uri.toString().equals("content://sms")) {
return;
}

OK

##提示

读取短信 需要权限

支付宝打赏 微信打赏

打赏