Android onReceiver()方法不起作用

时间:2016-01-14 06:26:10

标签: android broadcastreceiver sms

我希望我的应用程序通过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);
        }
    }

在主要活动中,我有这个代码来获取意图:

// 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>

请帮助。 非常感谢

1 个答案:

答案 0 :(得分:2)

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

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

此外,如果接收者类名称为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>