IntentService响应死亡的ResultReceiver

时间:2013-09-21 04:10:18

标签: android intentservice

活动实例化ResultReceiver并覆盖onReceiveResult。然后,活动将Intent发送到IntentService,并将ResultReceiver包含为额外的。一旦IntentService完成处理,它就会将消息发送回ResultReceiver并在onReceiveResult中处理它。

问题是,如果用户导航离开Activity,则结果仍然会发送回ResultReceiver,从而导致所有类型的问题。有没有办法阻止这种行为?我已经尝试在活动的onDestroy()中停止IntentService,但结果仍然被发回。

以下是活动示例

public class Foo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

    @Override
    public void onDestroy() {
        stopService(new Intent(this, SampleIntentService.class));
        mReceiver = null;
        super.onDestroy();
    }

    ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            // Handle response from IntentService here
        }
    };
}

以下是IntentService示例

public class SampleIntentService extends IntentService {
    public SampleIntentService() {
        super(SampleIntentService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
    ResultReceiver rec = intent.getParcelableExtra("receiver");
        if (rec != null) {
            rec.send(200, null);
        }
    }
}

1 个答案:

答案 0 :(得分:14)

我通过创建自定义ResultReceiver解决了这个问题,如下所示。

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);
        }
    }
}

然后在我的活动中,我执行以下操作:

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
    }
}

这将导致发送到您的自定义ResultReceiver的任何邮件在活动被销毁后无处可能结束:)