4

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

  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 发送短信。

谢谢你们的帮助。。

4

1 回答 1

5

看起来是因为你每次打电话sendRequest都会多注册BroadcastReceiver一次......

您应该BroadcastReceiver只注册一次,并且应该在进行活动之前取消注册......

只在链接中注册和未注册的工作onStart一次onStop

于 2012-06-14T10:31:49.477 回答