Android onReceiver() 方法无效

Android onReceiver() method not working

我希望我的应用程序通过 BroadcastReceiver 接收来自特定发件人的消息到我的应用程序中,不幸的是它不工作并且没有抛出任何错误, 下面是 BroadcastReceiver 的代码:

public void onReceive(Context context, Intent intent) {
        // Get Bundle object contained in the SMS intent passed in
        Bundle bundle = intent.getExtras();
        SmsMessage[]smsm=null;
        String sms_str = "";
        if (bundle != null) {
            // Get the SMS message
            Object[] pdus = (Object[]) bundle.get("pdus");
            smsm = new SmsMessage[pdus.length];
            for (int i = 0; i < smsm.length; i++) {
                smsm[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                sms_str += "Sent From: " + smsm[i].getOriginatingAddress();
                sms_str += "\r\nMessage: ";
                sms_str += smsm[i].getMessageBody().toString();
                sms_str += "\r\n";
            }
            Log.d("TAG", sms_str);

            // Start Application's  MainActivty activity
            Intent smsIntent = new Intent(context, MainActivity.class);
            smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            smsIntent.putExtra("sms_str", sms_str);
            context.startActivity(smsIntent);
        }
    }

在 Main Activity 中,我有这段代码来获取意图:

// Get intent object sent from the SMSBroadcastReceiver
        Intent sms_intent = getIntent();
        Bundle b = sms_intent.getExtras();
        if (b != null) {
            // Display SMS in the TextView
            txtViewSMS.setText(b.getString("sms_str"));
        }

我的清单文件有:

<!-- Declare SMS Broadcast receiver -->
        <receiver android:name=".SMSBReceiver"
            android:enabled="true">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

请提供帮助。 非常感谢

检查您是否在AndroidManifest.xml中拥有此权限:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

另外,如果接收者 class 的名字是 SMSBroadcastReceiver 那么这个名字必须在 AndroidManifest.xml:

中使用
<receiver android:name=".SMSBroadcastReceiver"
        android:enabled="true">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>