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

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

这是一个示例 Activity

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

最佳答案

我通过创建自定义 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);
        }
    }
}

然后在我的 Activity 中,我执行以下操作:
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 被销毁后都无处可去:)

关于android - IntentService 响应死的 ResultReceiver,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18928781/

10-08 21:11