2

我正在开发一个 android 短信应用程序。我必须向多个联系人发送短信。有一种方法可以向多个联系人发送短信,所以我使用了循环。以下是我的代码。

for (int i = 0; i < to_nums.size();i++) {

                sendSms(to_nums.get(i),  snd_txt.getText().toString() );


        }

public void sendSms(final String phoneNumber, final String message){


    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED),0);

   //--- When the SMS has been sent --

    sendBroadcastReceiver=new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            switch (getResultCode()) {

                case Activity.RESULT_OK:

                    Toast.makeText(getBaseContext(), "SMS sent",
                        Toast.LENGTH_SHORT).show();

                    break;

                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                        Toast.LENGTH_SHORT).show();

                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                        Toast.LENGTH_SHORT).show();



                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:

                    Toast.makeText(getBaseContext(), "Null PDU",
                        Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:

                    Toast.makeText(getBaseContext(), "Radio off",
                        Toast.LENGTH_SHORT).show();
                    break;



                default:
                    break;
            }
            context.unregisterReceiver(this);

        }
    };



    registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));






    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);





}

但是当我运行我的代码时,我遇到了一个异常,上面写着“接收器未注册”。对于单个收件人,它可以正常工作。.如何按顺序注册和注销?请朋友们帮帮我。

4

2 回答 2

1

您的问题是您为所有数字创建具有相同名称的新 Intent 对象的部分,这样做时,您将使用较新的数字覆盖已注册的广播,因此当较旧的广播捕获并运行 onReceive 函数时,它会发现它的没有注册了!您的解决方案是将 Intent 初始化更改为如下所示:

Intent i = new Intent(SENT_INTENT + phoneNumber);

交付意图也是如此,如果您的问题已解决,请告诉我

于 2013-12-31T18:14:36.467 回答