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