虽然这种方法可以用,但还是不怎么推荐,如果涉及到线程阻塞的问题,最好用AsyncTask来解决
new Thread(new Runnable() { public void run() { Looper.prepare(); //do something here //postReport(statusCode, url); Looper.loop(); } }).start();
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop();
关键在下面两个函数,相关说明可以在Looper.java(android.os.Looper)里找到
Looper.prepare(); Looper.loop();
android.os.Looper
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation of prepare and loop to create an initial Handler to communicate with the Looper.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}