when I put the setContentView in thread as below, it crashes while running in emulator.
new Thread(){
public void run() {
setContentView(R.layout.main_layout);
}
}.开发者_JAVA百科start();
that is because setContentView cannot be called from a non-UI thread.
You could try...
runOnUiThread(new Runnable(){
public void run() {
setContentView(R.layout.main_layout);
}});
.. but be careful as the convention is to do setContentView(..);
in onCreate()
on the default thread there.
Contents that should be displayed on the screen can only be called in the UI thread. The other threads have no access to UI elements. If you want to display something on the screen once your background thread is completed or notify something from the background thread you can use handler:
new Thread(new Runnable(){
public void run(){
//to do task in thread
Message msg=new Message();
msg.what=10;//specify some message content to check from which thread u r receiving the //message
handler.sendMessage(msg);
}
}).start();
and in handler:
Handler handler=new Handler(){
void handleMessage(Message msg){
if(msg.what==10){
//carry out any UI associaed task that you want
}
}
};
This method will ensure any thread that should run in background does not interfere wih UI thread, UI does not get slow, and you can update UI/ show dialogs by this method.
runInUIThread() method will put the thread in UI and the UI may become slow if your thread is downloading data form network or writing/reading from/to disk.
Hope this helps.
精彩评论