As the API said,the post() method should invoke in the thread which it attached,but there is occur some strange things that I can't explain!
the code is :
public class ProgressBarActivity extends Activity {
private final static String TAG = "ProgressBarActivity";
private Runnable test = new Runnable(){
@Override
public void run() {
try {
Thread.sleep(10000);
Log.i(TAG,"Thread---->"+Thread.currentThread().getId());
Log.i(TAG,"Thread---->"+Thread.currentThread().getName());
} catch (InterruptedException e) {}
}
};
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(test);
this.setContentView(R.layout.progress_bar_layout);
Log.i(TAG,"Activity--->"+Thread.currentThread().getId());
Log.i(TAG,"Activity--->"+Thread.currentThread().getName());
}
}
When 开发者_Go百科I install the app to the emulator with eclipse,what happended is that :the text in the onCreate() method first be printed!and after 10 seconds ,the text in the run() method is printed! Result is as below: Does someone know why?
06-04 14:13:09.964: INFO/ProgressBarActivity(366): Activity--->1
06-04 14:13:09.964: INFO/ProgressBarActivity(366): Activity--->main
06-04 14:13:20.070: INFO/ProgressBarActivity(366): Thread---->1
06-04 14:13:20.070: INFO/ProgressBarActivity(366): Thread---->main
You have it wrong: the docs here say this:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
That means the Runnable will be run on the Activity's main thread, but will be queued up and run AFTER the thread is done with its current work. The current work is completing onCreate
, so after onCreate
finishes the thread is now free and will process the Runnable. This is why you see the Activity text before the Runnable text: the current thread can not just stop what its doing and pick up the Runnable.
精彩评论