Android handler的问题:
package mars.handler;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class HandlerTest extends Activity {
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// sendMessage();
handler.post(r);
setContentView(R.layout.main); //System.out.println("1: " + System.currentTimeMillis());
// Thread t = new Thread(r) ;
// t.start();
System.out.println("a--->" + System.currentTimeMillis());
System.out.println("activity--->" + Thread.currentThread().getId());
System.out.println("activityname--->" + Thread.currentThread().getName());
}
Runnable r = new Runnable() {
public void run() {
//System.out.println("2: " + System.currentTimeMillis());
System.out.println("handler--->" + Thread.currentThread().getId());
System.out.println("handlername--->" + Thread.currentThread().getName()); try {
Thread.sleep(10000);
System.out.println("r2---?" + System.currentTimeMillis());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}按照执行的顺序:怎么这条语句:setContentView(R.layout.main);在两条System.out.println之前。而setContentView(R.layout.main);却是最后执行的?这是为什么?
package mars.handler;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class HandlerTest extends Activity {
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// sendMessage();
handler.post(r);
setContentView(R.layout.main); //System.out.println("1: " + System.currentTimeMillis());
// Thread t = new Thread(r) ;
// t.start();
System.out.println("a--->" + System.currentTimeMillis());
System.out.println("activity--->" + Thread.currentThread().getId());
System.out.println("activityname--->" + Thread.currentThread().getName());
}
Runnable r = new Runnable() {
public void run() {
//System.out.println("2: " + System.currentTimeMillis());
System.out.println("handler--->" + Thread.currentThread().getId());
System.out.println("handlername--->" + Thread.currentThread().getName()); try {
Thread.sleep(10000);
System.out.println("r2---?" + System.currentTimeMillis());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}按照执行的顺序:怎么这条语句:setContentView(R.layout.main);在两条System.out.println之前。而setContentView(R.layout.main);却是最后执行的?这是为什么?
这是异步过程,也就是说启动的r方法是异步线程启动的方法,可能会在 setContentView前,也可能在setContentView后,如果要实现LZ想要的那种效果,是同步,也就是按代码逐个执行