RECEIVE_SMS 的广播接收器在清单中声明时不工作(静态)

Broadcast Receiver for RECEIVE_SMS is not working when declared in manifest(statically)

我正在尝试检测收到的短信并通过 texttospeech 阅读它。

当我在 manifest 中声明广播接收器时,它不起作用。但它在 activity.

中动态完成时有效

我知道某些广播操作在清单中声明时无法在接收器中捕获,并且需要 activity(如前所述 here), but have seen people using RECEIVE_SMS in manifest as in here

我不知道我做错了什么。任何帮助将不胜感激!

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.bulsy.smstalk1">
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.READ_SMS" />
        <uses-permission android:name="android.permission.SEND_SMS"/>
        <uses-permission android:name="android.permission.READ_CONTACTS" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <receiver android:name="com.bulsy.smstalk1.SmsListener"
                   android:enabled="true" 
                   android:permission="android.permission.BROADCAST_SMS"
                   android:exported="true">   
                <intent-filter android:priority="2147483647">//this doesnt work
                    <category android:name="android.intent.category.DEFAULT" />
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>
        </application>   
    </manifest>

SmsListener.java

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;
    TextToSpeech textToSpeech;
    String msg_from;
    public SmsListener()
    {

    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){

            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;

            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        final String msgBody = msgs[i].getMessageBody();
                        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
                            @Override
                            public void onInit(int status) {
                                if(status != TextToSpeech.ERROR) {
                                    textToSpeech.setLanguage(Locale.UK);
                                    String fromName = getContactName(context,msg_from);
                                    fromName = fromName==null? msg_from:fromName;
                                    textToSpeech.speak("You have a text message from " + fromName + ". Content: " + msgBody , TextToSpeech.QUEUE_FLUSH, null);
                                }
                            }
                        }
                        );


                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }

MainActivity.java

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SmsListener smsListener = new SmsListener();//Dynamically setting the receiver. this works.
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        this.registerReceiver(smsListener,filter);
    }
}

这里问题的根源在于清单注册的 Receiver 实例的生命周期。此类 Receiver 的实例将仅在 onReceive() 方法完成之前处于活动状态。 TextToSpeech 对象在 Receiver 死亡之前不会就绪,并且没有任何其他 Receiver 工作指示,看起来好像 Receiver 刚刚失败。

解决方案是将 TextToSpeech 功能移动到 Service,您可以从接收器 运行,并将必要的信息作为附加信息传递给所用的 Intent开始吧。