我在手动结束 IntentService onHandleIntent 方法时遇到了一些麻烦。我正在捕获一个异常,这对线程的其余部分的执行至关重要,我想在捕获异常时停止线程。我尝试调用 stopSelf() 或直接调用 onDestroy() ,我敢肯定这可能是非常糟糕的方法,而且它们不起作用。线程调用它们然后继续。
有人对如何做到这一点有任何好主意吗?
我在手动结束 IntentService onHandleIntent 方法时遇到了一些麻烦。我正在捕获一个异常,这对线程的其余部分的执行至关重要,我想在捕获异常时停止线程。我尝试调用 stopSelf() 或直接调用 onDestroy() ,我敢肯定这可能是非常糟糕的方法,而且它们不起作用。线程调用它们然后继续。
有人对如何做到这一点有任何好主意吗?
正如 sonykuba 所说,完成 onHandleIntent 方法会停止服务。所以你可以做这样的事情:
public void onHandleIntent {
try {
// ... your code here
} catch(YourException e) {
// do something with the exception
return; // this prevents the rest of the method from execution
// and thereby stops the service
}
// rest of your code
}
IntentService 在完成 OnHandleIntent 后自动停止。无需手动进行。