I want to use a menu to send a message to handler. And handler started a thread to update from server.
However, when I tested my app, I closed down the server and pressed the menu. The android app is blocked in the menu which should not happen because the menu just send a message. Therefore my UI was blocked.
Here is the code
final Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.arg2) {
case 0:
int total = msg.arg1;
progressDialog.setProgress(total);
if (total >= progressDialog.getMax()) {
// 取消Dialog并且置0
dismissDialog(PROGRESS_DIALOG);
progressDialog.setProgress(0);
Toast.makeText(CardProcessView.this, "下载完成",
Toast.LENGTH_SHORT).show();
initData();
}
break;
case 1:
updatabase();
break;
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Message message = new Message();
message.arg2 = 1;
messageHandler.sendMessage(message);
break;
default:
Log.d("update", "未更新");
}
return true;
}
protected void updatabase() {
new Thread(updateRunable ).run();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("更新操作向导");
return true;
}
I can’t find my answer. Thank you for everyone.
you need change:
to:
thread.run()just invoke the thread’s run method, dont start the method in a new thread, you need invokethread.start()to make a thread and invokerunmethod in this new thread.