2

我在我的代码中动态注册了 2 个接收者以获取发送短信的结果和发送状态,我无法创建新类,这必须在现有类(扩展对话框)中完成。如何注销接收器。

我已经阅读了其他帖子,但它们没有帮助,它们要么有一个单独的类,要么在 xml 清单中注册接收器。

这是我的代码

private void sendSMS(String keyword, String msisdn) { 

   String SENT = "SMS_SENT";
   String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0,
           new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,
           new Intent(DELIVERED), 0);

    mContext.registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    sendEventLog("Failed(Generic failure)");    
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    sendEventLog("Failed(No service)");     
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    sendEventLog("Failed(Null PDU)");   
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    sendEventLog("Failed(Radio off)");  
                    break;
            }
        }
    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---
    mContext.registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    break;
                case Activity.RESULT_CANCELED:
                    sendEventLog("Failed(SMS not delivered)"); 
                    break;
            }
        }
    }, new IntentFilter(DELIVERED));

   SmsManager MySmsManager = SmsManager.getDefault();
       MySmsManager.sendTextMessage(msisdn, null, keyword, sentPI, deliveredPI);

    }
4

2 回答 2

0

除了跟踪接收者之外,您似乎别无选择。

另请参阅我是否需要为此主题取消注册“匿名”BroadcastReceiver。

于 2013-01-28T10:54:11.007 回答
0

您只需存储对您即时创建的接收器的引用。

BroadcastReceiver rcv;
rcv = new BroadcastReceiver() { ... }
mContext.registerReceiver(rcv);

使用此引用 ( rcv),您可以取消注册它。

于 2013-01-28T10:51:17.923 回答