java识别Oreo中的sms号码ID
我的实际代码完美地阻止了调用,但现在我想识别一个传入的SMS号码ID并做一些事情,比如标记为read或其他什么(比如Medium和thisone)
我读过几篇文章和帖子,但都没有达到目的,请再次注意,这段代码可以完美地阻止呼叫,因此我将粘贴与SMS相关的信息
舱单。xml
<uses-permission 安卓:name="安卓.permission.RECEIVE_SMS" />
<uses-permission 安卓:name="安卓.permission.READ_SMS" />
<service 安卓:name=".CallReceiverService" />
广播接收机服务
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new Notification.Builder(this, SERVICE_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(this.getResources().getString(R.string.stg_ServiceRunning))
.setContentIntent(pendingIntent)
.setCategory(Notification.CATEGORY_CALL)
.build();
startForeground(44332255, notification);
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("安卓.intent.action.PHONE_STATE"); // related to call feature, ignore
intentFilter.addAction("安卓.provider.Telephony.SMS_RECEIVED");
intentFilter.addAction("Telephony.Sms.Intents.SMS_RECEIVED_ACTION");
intentFilter.setPriority(1000);
registerReceiver(callCheckReceiver, intentFilter);
}
private BroadcastReceiver callCheckReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Log.d("Call", "SMS received");
String smsSender = "";
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Log.d("Call", "SMS received");
String smsSender = "";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getDisplayOriginatingAddress();
}
if (!isValidPhoneNumber(smsSender)) {
Log.d("Call", "Invalid SMS detected: From " + smsSender);
}
}
if (!isValidPhoneNumber(smsSender)) {
Log.d("Call", "Invalid SMS detected: From " + smsSender);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static boolean isValidPhoneNumber(String phoneNumber) {
return 安卓.util.Patterns.PHONE.matcher(phoneNumber).matches();
}
基本上,我在MainActivity中请求权限,在Manifest中设置它们,并在Oreo或更低版本的Android中正确调用的服务中传递FilterContent。目标空气污染指数>=十九,
我不想建立一个应用程序来管理短信,我只想截取号码ID并做一些事情。有人能提供建议吗
# 1 楼答案
你需要的是SMS Retriever API
如果你想检测短信,你可以简单地使用
在AndroidManifest中。xml只需添加接收者
在接收器中,您可以对检测到的消息执行任何操作
需要注意的是,SMSRetrieverClient默认超时为5分钟
要创建可检测短信,请遵循SMS Creator for Google