IntentService responding to dead ResultReceiver

前端 未结 1 545
暗喜
暗喜 2021-02-06 09:10

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

相关标签:
1条回答
  • 2021-02-06 09:54

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

    public class SampleResultReceiver extends ResultReceiver {
        private Receiver mReceiver;
    
        public SampleResultReceiver(Handler handler) {
            super(handler);
        }
    
        public void setReceiver(Receiver receiver) {
            mReceiver = receiver;
        }
    
        public interface Receiver {
            void onReceiveResult(int resultCode, Bundle resultData);
        }
    
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            if (mReceiver != null) {
                mReceiver.onReceiveResult(resultCode, resultData);
            }
        }
    }
    

    Then in my Activity I do the following:

    public class Foo extends Activity implements Receiver {
        private SampleResultReceiver mReceiver;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            mReceiver = new SampleResultReceiver(new Handler());
            mReceiver.setReceiver(this);
    
            Intent i = new Intent(this, SampleIntentService.class);
            i.putExtra("receiver", mReceiver);
            startService(i);
        }
    
        @Override
        public void onDestroy() {
            if (mReceiver != null) {
                mReceiver.setReceiver(null);
            }
            super.onDestroy();
        }
    
        @Override
        protected void onReceiveResult(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 :)

    0 讨论(0)
提交回复
热议问题