进来编写了一个小程序,想测试一下消息队列中语句的输出顺序,及实现的Runnable接口r是否和activity这个线程在同一个线程内,结果为:
(1)activityId->
(2)activityName-> (3)threadId->
(4)threadName->import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class HandlerTest2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.post(r);
System.out.println("(1)activityid-->"+Thread.currentThread().getId());
System.out.println("(2)activityid-->"+Thread.currentThread().getName());
}
Handler handler = new Handler();
Runnable r= new Runnable(){ public void run() {
System.out.println("(3)threadId->"+Thread.currentThread().getId());
System.out.println("(4)threadName->"Thread.currentThread().getName());
}
};
}为什么不是:
(3)threadId->
(4)threadName-> (1)activityId->
(2)activityName->按照程序的执行顺序,先执行handler.post(r);
调用的是r对象中的run()先输出(3)(4)才对啊 。。怎么先输出(1)(2)啊?????????
请高手赐教。
(1)activityId->
(2)activityName-> (3)threadId->
(4)threadName->import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class HandlerTest2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.post(r);
System.out.println("(1)activityid-->"+Thread.currentThread().getId());
System.out.println("(2)activityid-->"+Thread.currentThread().getName());
}
Handler handler = new Handler();
Runnable r= new Runnable(){ public void run() {
System.out.println("(3)threadId->"+Thread.currentThread().getId());
System.out.println("(4)threadName->"Thread.currentThread().getName());
}
};
}为什么不是:
(3)threadId->
(4)threadName-> (1)activityId->
(2)activityName->按照程序的执行顺序,先执行handler.post(r);
调用的是r对象中的run()先输出(3)(4)才对啊 。。怎么先输出(1)(2)啊?????????
请高手赐教。
这样情况,因为1和2的输出在Looper取出消息之前就完成了。
而handler需要等activity初始化完成后才会运行。
对。。Handler确实是在onResume之后才运行,自己实验了一下,受教了