我有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