-2

我正在用 SmsReceiver 编写一个应用程序。我希望此类接收包含特殊单词的消息文本,例如“SPY”,并且不要让其他接收者接收此类消息。我该怎么做?
这是接收器类

package com.newidea.repairmycontacts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.telephony.SmsMessage;


public class SmsReceiver extends BroadcastReceiver {
    private final static String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private final String TAG = "SmsReceiver";


@Override
public void onReceive(Context context, Intent intent) {
    //onReceiveWithPrivilege(context, intent, false);
    if(!intent.getAction().equals(SMS_RECEIVED))
        return;
    Bundle bundle = intent.getExtras();
    if(bundle==null)
        return;
    Object[] pdus=(Object[]) bundle.get("pdus");
    String Body="";
    for(int i=0;i<pdus.length;i++)
        Body += SmsMessage.createFromPdu((byte[]) pdus[i]).getMessageBody().toString()+"\n";
    String Address=SmsMessage.createFromPdu((byte[]) pdus[0]).getOriginatingAddress();

    Toast.makeText(context, "Message from "+Address+" : "+Body, Toast.LENGTH_LONG).show();
   }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.newidea.repairmycontacts"
android:versionCode="1"
android:versionName="1.0" >
   <uses-permission android:name="android.permission.RECEIVE_SMS"/>
   <uses-permission android:name="android.permission.READ_SMS"/>
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar" >
    <activity
        android:name="com.newidea.repairmycontacts.SMSList"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name=".SmsReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>
</application>

4

1 回答 1

3

您必须为 .SmsReceiver 设置意图过滤器标签的优先级,如下所示:

<receiver android:name=".SmsReceiver">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

请注意,这将适用于股票消息应用程序,但其他一些短信应用程序使用其他优先级并且可能会超过您的优先级......

之后如果要阻止其他应用接收广播,可以使用:

BroadcastReceiver.abortBroadcast()

请记住,这对于其他短信应用程序来说特别脆弱。

于 2013-08-29T09:36:27.750 回答