【问题标题】:SMS BroadCast Receiver receives many times?SMS广播接收器接收多次?
【发布时间】:2018-05-01 17:12:32
【问题描述】:

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

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

谢谢你们的帮助..

【问题讨论】:

    标签: android sms broadcastreceiver


    【解决方案1】:

    看起来是因为每次您拨打 sendRequest 时,您都会多注册一次 BroadcastReceiver ......

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

    只在onStartonStop 中注册和未注册的工作一次,就像在link 中一样

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多