Skip to content Skip to sidebar Skip to footer

Intentservice Responding To Dead Resultreceiver

An activity instantiates a ResultReceiver and overrides onReceiveResult. The activity then sends an Intent to an IntentService and includes the ResultReceiver as an extra. Once the

Solution 1:

I solved this issue by creating a custom ResultReceiver as follows.

publicclassSampleResultReceiverextendsResultReceiver {
    private Receiver mReceiver;

    publicSampleResultReceiver(Handler handler) {
        super(handler);
    }

    publicvoidsetReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    publicinterfaceReceiver {
        voidonReceiveResult(int resultCode, Bundle resultData);
    }

    @OverrideprotectedvoidonReceiveResult(int resultCode, Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode, resultData);
        }
    }
}

Then in my Activity I do the following:

publicclassFooextendsActivityimplementsReceiver {
    private SampleResultReceiver mReceiver;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReceiver = newSampleResultReceiver(newHandler());
        mReceiver.setReceiver(this);

        Intenti=newIntent(this, SampleIntentService.class);
        i.putExtra("receiver", mReceiver);
        startService(i);
    }

    @OverridepublicvoidonDestroy() {
        if (mReceiver != null) {
            mReceiver.setReceiver(null);
        }
        super.onDestroy();
    }

    @OverrideprotectedvoidonReceiveResult(int resultCode, Bundle resultData) {
        // Handle response from IntentService here
    }
}

This will cause any messages sent to your custom ResultReceiver to end up nowhere after the Activity has been destroyed :)

Post a Comment for "Intentservice Responding To Dead Resultreceiver"