SMS BroadCast接收器多次收到?

时间:2012-06-14 10:24:02

标签: android sms broadcastreceiver

我在我的应用程序中使用短信广播接收器。当我发送第一个短信时,它会弹出一条短信作为短信发送。当我发送第二个请求时,弹出消息加倍。它第三次增加了三倍,等等。我使用以下代码发送和接收广播。

  private void sendRequest()
    {        
        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---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                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(), "Invalid PhoneNumber", 
                                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;
                }
            } 
        }, new IntentFilter(SENT));


       SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(sms_phonenumber, null, sms_message, sentPI, null);  

我不确定这是否正在发生。我正在从mainactivity发送短信。

感谢您的帮助..

1 个答案:

答案 0 :(得分:5)

看起来是因为每次拨打sendRequest时,您再次注册BroadcastReceiver ........

您应该只注册BroadcastReceiver一次,并且在参加活动之前应该注销[...}

仅在onStartonStop link

进行一次注册和未注册的工作