1.Looper
Looper 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.
2.HandlerThread 为我们解决问题
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start()
must still be called.
public class HandlerThread extends Thread { Looper mLooper; protected void onLooperPrepared() { } public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); //为mLooper赋值,唤醒等待的线程 } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } public Looper getLooper() { if (!isAlive()) { //线程是否启动 return null; } synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); // 如果mLooper为null则等待 } catch (InterruptedException e) { } } } return mLooper; } }
3.使用HandlerThread
HandlerThread thread = new HandlerThread("handlerThread"); thread.start(); Looper looper = thread.getLooper(); Handler handler = new ServiceHandler(looper); //传入Looper参数,初始化Handler