7

一个活动实例化一个 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);
        }
    }
}
4

1 回答 1

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 的任何消息在 Activity 被销毁后无处可去:)

于 2013-09-21T04:10:17.900 回答