我正在編寫一個包含ExecutorService的單例類的SDK。它看起來是這樣的:如何在Android應用程序中使用ExecutorService關閉
public class MySingleton {
private static MySingleton mInstance;
private ExecutorService mExecutorService;
private MySingleton() {
mExecutorService = Executors.newSingleThreadExecutor();
}
// ...
public void doSomething(Runnable runnable) {
mExecutorService.execute(runnable);
}
}
此SDK類的目的是在整個應用程序中使用運行的任務/的Runnable,並DoSomething的()函數是在一個單獨的線程排隊和運行所有的Runnable。
但我無法弄清楚的一件事是何時調用ExecutorService。 shutdown()方法。如果我把它像這樣:
public void doSomething(Runnable runnable) {
if (mExecutorService.isTerminated()) {
mExecutorService = Executors.newSingleThreadExecutor();
}
mExecutorService.execute(runnable);
mExecutorService.shutdown();
}
這將破壞使用一個線程,因爲如果舊的Runnable仍在運行時DoSomething的()被稱爲第二次,也有可能同時運行兩個不同的線程的目的。當然,我可以有一個手動關閉ExecutorService的函數,但要求SDK的用戶顯式調用關閉函數似乎並不合適。
任何人都可以告訴我什麼時候/如何在Android應用程序中調用ExecutorService.shutdown()?謝謝
您應該在完成使用該服務後關閉。據推測,這是你的應用程序退出時。 – shmosel
@shmosel感謝您的回覆。我明白,當Im完成服務時,Im應該關機。但我的問題更多的是如何看待Android框架?是否有聽衆在應用程序關閉時收聽? (有onStop()和onDestroy(),但那些是用於活動)。 – baekacaek