note. UI control is available only in main thread(UI thread).
1. create handler in main thread
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
public class main extends Activity {
public Handler _handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// where the main activity thread receives messages
// do what we want
showMyDialog();
super.handleMessage(msg);
}
};
public void showMyDialog()
{
//show ui
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//...
}
}
2. use Message in other work thread
//in another thread
public void sendMessageToShowDialog() {
//--------------------------
//call showMyDialog() directly will cause exception because here is not in ui thread.
//m_parents.showMyDialog();
//-------------------------
//-----------------------------
//send message to show dialog
Message msg = Message.obtain();
//User-defined message code
msg.what = 999;
m_parents._handler.sendMessage(msg);
//------------------------------
}
沒有留言:
張貼留言