Android 10+ 版本提供了内置的防止垃圾短信的筛选器,使用户能够自动过滤不需要的短信。以下是如何在 Android 10+ 上使用反垃圾短信筛选器的示例代码:
1.添加权限 to AndroidManifest.xml
2.添加筛选器 to AndroidManifest.xml
3.实现与用于数据匹配的正则表达式相匹配的 SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
if (pdusObj != null) {
for (Object pdu : pdusObj) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
String sender = sms.getDisplayOriginatingAddress();
String message = sms.getDisplayMessageBody();
if (!isSpam(sender, message)) {
// TODO Do whatever you want with the valid message
Log.i(TAG, "Valid SMS received, sender: " + sender + ", message: " + message);
} else {
// TODO Do whatever you want with the spam message
Log.i(TAG, "Spam SMS received, sender: " + sender + ", message: " + message);
}
}
}
}
}
}
private boolean isSpam(String sender, String message) {
// TODO Implement