发送没有收到的短信广播

时间:2018-03-29 12:57:43

标签: android android-pendingintent android-broadcastreceiver smsmanager

我必须发送短信并在发送时采取行动,我使用广播待定意图广播状态如下。

BroadcastReceiver smsStatusReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();}
};

@Override
    protected void onCreate(Bundle savedInstanceState) {
        mBroadcastManager = LocalBroadcastManager.getInstance(this);
        mBroadcastManager.registerReceiver(smsStatusReceiver, new IntentFilter(ACTION_SENT));
        mBroadcastManager.registerReceiver(smsStatusReceiver, new IntentFilter(ACTION_DELIVERED));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.sendSMS(MainActivity.this, "123456", "test", ACTION_SENT, ACTION_DELIVERED);
            }
        });
    }
在实用工具中

public static void sendSMS(Activity activity, String destination, String text, String sentAction, String deliveryAction) {    
        PendingIntent sentPI = null;
        PendingIntent deliveredPI = null;
        if (!TextUtils.isEmpty(sentAction)) {
            sentPI = PendingIntent.getBroadcast(activity, 0, new Intent(sentAction), 0);
        }
        if (!TextUtils.isEmpty(deliveryAction)) {
            deliveredPI = PendingIntent.getBroadcast(activity, 500, new Intent(deliveryAction), 0);
        }
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(destination, null, text, sentPI, deliveredPI);
    }

虽然短信发送成功,但永远不会调用onReceive(),无法在文档中找到任何不直接的内容。 知道发生了什么事吗?

2 个答案:

答案 0 :(得分:1)

您是否在Manifest类中添加了BroadcastReceiver?

<receiver android:name=".receiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
</receiver>

答案 1 :(得分:1)

使用sms.sendTextMessage(phoneNumber, null, message, sentPI, null);发送短信时,您可以提供待处理的意图(sentPI),以便在收到时通知。

If not NULL this PendingIntent is broadcast when the message is delivered to the recipient. The raw pdu of the status report is in the extended data ("pdu").

您可以将BroadcastReceiver提供为PendingIntent:

Intent intentWithData = new Intent(context, SMSDeliveredBroadcastReceiver.class);
intentWithData.putExtra("number",number);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 7, intentWithData, 0);
相关问题