1, first of all explain why AsyncTask must be created in the main thread? ? ?
- In "Android explore the development of art," the book is explained. Due to the use of AsyncTask Handler main thread. To be able to switch to the main thread execution environment, which requires Handler object must be created in the main thread. And this is a static member variables AsyncTask Handler's. Because static members will be initialized when the class is loaded, so this requires AsyncTask disguise the class must be loaded in the main thread.
- Personally I think that this view is wrong.
- View 1: If you want to switch to the main thread execution environment, do not have to create Handler in the main thread. As long as when Handler created using UI thread looper can.
As shown in the following code: handler can create sub-thread, since the transfer is created when the main thread of the looper, so the message will be forwarded to the loop processing handleMessage main thread.
- View 1: If you want to switch to the main thread execution environment, do not have to create Handler in the main thread. As long as when Handler created using UI thread looper can.
new Thread(new Runnable() {
@Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Log.d("lichaojun", "handleMessage: " + Thread.currentThread());
break;
default:
break;
}
}
};
handler.sendEmptyMessage(1);
}
}).start();`
- 观点2:观点1的解释,也就说明了AsyncTask可以在子线程中加载。虽然handler是静态成员,但是根据观点1的解释,Handler也可以在子线程中加载