在 IntentService 中使用 RoboSpice。在 CountDownLatch 的帮助下解决了这个问题。假设我们有 2 个不同的 SpiceManagers 和一些 syncMethods 在 IntentService 中按顺序执行。
全局:
private final SpiceManager aSpiceManager =
new SpiceManager(ASpiceService.class);
private final SpiceManager bSpiceManager =
new SpiceManager(BSpiceService.class);
private CountDownLatch handleIntentLatch;
onHandleIntent:在我们执行 syncMethodA 之前 - 我们用 1 初始化我们的 CountDownLatch。在执行 syncMethodA 之后,我们在我们的锁存器上 await() for countDown()。当稍后某些方法将在我们的闩锁上调用 countDown() 至少一次 - 方法 onHandleIntent 将继续执行并完成,这将触发 IntentService onDestroy() 回调。
@Override
protected void onHandleIntent(Intent intent) {
handleIntentLatch = new CountDownLatch(1);
syncMethodA();
try {
handleIntentLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
syncMethodA():
假设我们需要依次启动一些同步方法(syncMethodA,其中回调执行syncMethodB等)。
private void syncMethodA() {
SpiceRequest requestA = new SpiceRequest();
if (!aSpiceManager.isStarted()) {
LogUtils.LOGD(TAG, "starting aSpiceManager");
aSpiceManager.start(getApplicationContext());
}
aSpiceManager.execute(requestA , new RequestListener<ResponseA>() {
@Override
public void onRequestSuccess(final ResponseA responseA) {
// SOME LOGIC
syncMethodB();
// SOME LOGIC
@Override
public void onRequestFailure(SpiceException spiceException) {
handleIntentLatch.countDown();
// SOME LOGIC
}
});
}
syncMethodB、syncMethodC 等都是一样的——在 onRequestSuccess 我们开始下一个 syncMethodX。在 onRequestFailure 中,我们 countDown() 我们的闩锁 (handleIntentLatch)。
非常重要!!!
在顺序的最后一个 syncMethodX 中(完成后我们希望 onHandleIntent 方法继续执行并完成这将导致 IntentService 停止) - 我们 countDown() 我们在 onRequestSuccess ALSO 中的锁存器.
onDestroy:在这里我们停止我们的 SpinceManagers。
@Override
public void onDestroy() {
super.onDestroy();
LogUtils.LOGD(TAG, "onDestroy");
shutDownSpiceManagers();
}
shutDownSpiceManagers:
private void shutDownSpiceManagers() {
if (aSpiceManager.isStarted()) {
LogUtils.LOGD(TAG, "stopping aSpiceManager");
aSpiceManager.shouldStop();
}
if (bSpiceManager.isStarted()) {
LogUtils.LOGD(TAG, "stopping bSpiceManager");
bSpiceManager.shouldStop();
}
}
现在一切都应该好了:没有泄露的上下文,SpiceManagers 将在 onDestroy 中被杀死 并且仅在解决回调之后。