複数のスレッドを作成する Android アプリケーションがあります。一部のスレッドは、スレッドセーフな HttpClient を使用して、サーバーから継続的にデータを取得します。
例 1: スレッド 1 -> サーバーからデータを取得したので、ダイアログを表示してユーザーに通知する必要があります。例 2: スレッド 2 -> (UI スレッドで) モーダル PendingDialog を表示 -> スレッド 2 を開始 -> サーバーにデータを投稿し、応答を確認 (UI スレッドではない) -> runOnUiThread() { rejectPendingDialog()...}
基本的に私はスレッドを作成しています:
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()
それぞれ。
「一度に1つのダイアログを表示」を成功させています。ただし、ユーザーがいくつかのアクションを実行すると問題が発生します。たとえば、次のようになります。
- アプリケーションを終了します
- 新しいアクティビティに移動
- ホームなどに移動します。
ダイアログを表示すると (注: UI スレッドで) 、などWindowManager$BadTokenException
の例外が発生することがあります。IllegalStateException
MyActivity has leaked window
前に確認できますdialog.show()
:
if(!Thread.interrupted() && shouldRun && !activityGivenInConstructor.isFinishing())
ただし、これはアプリケーションの問題からの終了のみを解決します。他の状況では、いくつかの例外が発生します。
これをどのように実装すればよいですか?もう例外はないということですか?そして、この check/if(!Thread.interrupted()... 例外の発生を防ぐためにできることはすべてですか?