Skip to content Skip to sidebar Skip to footer

Is It Ok To Unregister 'dynamic' Broadcastreceiver From Receiver's Own Onreceive() Method?

That is, I have this BroadcastReceiver I create on the fly to listen for one broadast, after which I want it to unregister itself. I haven't found any sample code that does it thi

Solution 1:

The answer to your question is "yes". However...

...you need to call unregisterReceiver() on the same Context that you called registerReceiver() on. In the code you posted you are calling unregisterReceiver() on the Context passed in as an argument to onReceive(). This is not the same Context which is why you are getting the exception.

Solution 2:

I would simply say YES, no problem at all.

I use it for a one-time location fix for example, and can be used in other logics too without me seeing any problem to it.

Plus I've seen it around many times.

Solution 3:

I have tried various solutions, finally I am doing it that way:

Registering:

MyApplication.getInstance().getApplicationContext().registerReceiver(sentReceiver, new IntentFilter(SENT));

SentReceiver:

publicclassSentReceiverextendsBroadcastReceiver  {
    publicvoidonReceive(Context context, Intent arg1) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context,
                        context.getString(R.string.sms_envoye), Toast.LENGTH_SHORT)
                        .show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context,
                        context.getString(R.string.sms_defaillance_generique),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(context,
                        context.getString(R.string.sms_pas_de_service),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(context,
                        context.getString(R.string.sms_pas_de_pdu),
                        Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(context,
                        context.getString(R.string.sms_radio_desactivee),
                        Toast.LENGTH_SHORT).show();
                break;
        }
        MyApplication.getInstance().getApplicationContext().unregisterReceiver(this);
    }

With MyApplication:

publicclassMyApplicationextendsApplication {
    privatestatic MyApplication mInstance;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        mInstance = this;
    }

    publicstaticsynchronized MyApplication getInstance() {
        return mInstance;
    }        
}

Post a Comment for "Is It Ok To Unregister 'dynamic' Broadcastreceiver From Receiver's Own Onreceive() Method?"