使用循环将短信发送到多个联系人

时间:2012-09-05 07:41:43

标签: android broadcastreceiver

我正在开发一个android sms应用程序。我必须发送sms到多个contact.There方法可用于发送短信到多个联系人所以我用于循环。以下是我的代码。

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);





}

但是当我运行我的代码时,我得到一个例外,即“接收者没有注册”#39;对于单个收据,它可以工作。 。如何按顺序注册和注销?请帮帮我朋友。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

您的问题是您为所有数字创建具有相同名称的新Intent对象的部分,在执行此操作时,您将使用较新的数字覆盖已注册的广播,因此当旧版本捕获广播并运行onReceive函数时发现它还没有注册! 您的解决方案是将Intent初始化更改为以下内容:

  

意图i =新意图(SENT_INTENT + phoneNumber);

和交付意图相同,请告诉我您的问题是否已解决