我有Android應用程序可以創建多個線程。一些線程使用線程安全的HttpClient不斷從服務器獲取數據。多線程處理和對話框顯示/解除在Android中提供例外
示例1:線程1 - >從服務器獲取數據,現在我必須顯示Dialog來通知用戶。 ());(2)在線程2 - >(在UI線程上)顯示模式PendingDialog - >啓動線程2 - >在服務器上發佈數據並檢查響應(不在UI線程上) - > runOnUiThread(){dismissPendingDialog()... }
基本上我創建線程有:
classRunnableInstance = new MyRunnable(...);
classThreadInstance = new Thread(classRunnableInstance);
classThreadInstance.start();
和 「取」 線程的基本結構是:
public void run() {
try {
while(shouldRun) {
SomeResultObj result = MyHttpClient.invokeSomeMethod();
if(checkIfIMustInformUser(result)) {
inform();
}
sleep();
}
}
catch(IOException e) {
activityGivenInConstructor.showFetchingDataError(e); //show on UI-thread
}
}
protected void inform(final SomeResultObj result) {
activityGivenInConstructor.runOnUiThread(new Runnable() {
public void run() {
Dialog dialog = MyDialogUtils.create(context, messageId);
...
dialog.show();
//or pendingDialog.dismiss();
}
});
shouldRun = false;
return;
}
protected void sleep() {
try {
Thread.sleep(AppConstants.SLEEP_DELAY);
}
catch(InterruptedException e) {
shouldRun = false;
}
}
而且我停止和啓動線程:onPause()
和onResume()
分別。
我正在處理「一次顯示一個對話框」成功。但是,當用戶執行某些動作出現問題 - 例如:
- 退出應用
- 轉到新的活動
- 轉到主頁等
當我告訴對話框(注:上UI線程)也有例外,有時像WindowManager$BadTokenException
,IllegalStateException
,MyActivity has leaked window
等
我可以檢查dialog.show()
前:
if(!Thread.interrupted() && shouldRun && !activityGivenInConstructor.isFinishing())
但這解決了只退出應用程序問題。在其他情況下有一些例外。
我該如何實施?那不會有更多的例外嗎? 這是檢查/如果(!Thread.interrupted()...所有我可以做,以防止上升的異常?
考慮到這種情況:我將數據這個數據可以在任何時候改變,例如'boolean'。如果'boolean'是'true',那麼我會通知用戶,如果它是'false',那麼什麼都不會發生,用戶可以使用這個活動「屏幕」)沒有任何分心。 – Xeon