@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }从代码中可以看出调用的Looper类中的prepare()方法和loop()方法,并且得到了Looper对象。这些主要是对自己做一些初始化。 我们是如何使用HandlerThread类的,下面写了简单的代码:
public class MainActivity extends Activity { private HandlerThread mHandlerThread = null; private Handler mThreadHandler = null; private Handler mUIHandler = null;//主线程(UI线程)中的Handler对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); mThreadHandler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub //这里 Toast.makeText(MainActivity.this, "线程名字 === " + Thread.currentThread().getName(), Toast.LENGTH_LONG).show(); } }); mUIHandler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "线程名字 === " + Thread.currentThread().getName(), Toast.LENGTH_LONG).show(); } }, 4000); } private void init() { mHandlerThread = new HandlerThread("HandlerThread");//这里的构造函数是给该HandlerThread一个名字 mHandlerThread.start();//调用start()方法即run()方法初始化Looper mThreadHandler = new Handler(mHandlerThread.getLooper());//得到HandlerThread中的Looper对象 mUIHandler = new Handler(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
就是主线程: