我们在 Android 中是否有一个选项来验证短信文本字词,然后再将其显示在屏幕上给用户?我可以用特定文本阻止这条短信,用代码控制它吗?
关于这件事的任何想法或教程?
如下创建广播接收器
public class SMSReceiver extends BroadcastReceiver {
private List<NameValuePair> nameValuePairs;
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null)
return;
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage
.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
Log.e("message: ", body);
Log.e("Number", sender);
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra(
"get_msg", sender + ":" + body);
context.sendBroadcast(in);
if (body.equals("your text") {
this.abortBroadcast();
}
}
}
}
在清单中将您的接收器注册为
<receiver
android:name="yourpackagename.SMSReceiver"
android:exported="true" >
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
这会成功的。希望这可以帮助。:)
您可以使用 BroadcastReceiver 来获取传入的短信
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
// Log.i(TAG, "Intent received: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length > -1) {
String str=messages[0].getMessageBody();
if(check for the text in the string str)
{
abortBroadcast();//stops msg from reaching inbox
}
}
}
}
}
}
将这些权限添加到您的清单
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
将接收器添加到您的清单
<receiver android:name=".SmsReceiver" >
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" >
</action>
</intent-filter>
</receiver>