【发布时间】:2012-05-17 20:33:02
【问题描述】:
我有创建多个线程的 Android 应用程序。有些线程使用线程安全的HttpClient不断从服务器获取数据。
示例 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())
但这只能解决退出应用程序问题。在其他情况下会出现一些例外情况。
我应该如何实现这个?不会再有例外了? 这个 check/if(!Thread.interrupted()... 我能做的就是防止异常上升吗?
【问题讨论】:
标签: java android multithreading exception dialog