HandlerThread的使用

HandlerThread其实是Thread 的一个子类,官方给的解释是

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.

其实是为启动一个具有Looper的线程而写的类,这个looper 能够用于创建一个Handler类,注意start()方法必须被调用。

详细说明见官网:http://developer.android.com/reference/android/os/HandlerThread.html
         参考其他人资料:http://blog.csdn.net/wanglong0537/article/details/6304239
 Demo :
public class MyHandlerThread extends HandlerThread {
	private static final String TAG = "MyHandlerThread";
	private Handler mHandler;


	public MyHandlerThread(String name) {
		super(name);
	}
	
	public Handler getHandler() {
		return mHandler;
	}


	@Override
	public void start() {
		super.start();
		Looper looper = getLooper(); // will block until Looper is initialized
		mHandler = new Handler(looper) {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				// process messages here
				}
			}
		};
	}
}

调用该类时的demo片段:
	MyHandlerThread thread = new MyHandlerThread("handler thread");
        thread.start();
        
        // later...
        Handler handler = thread.getHandler(); // careful: this could return null if the handler is not initialized yet
        
        // to post a runnable
        handler.post(new Runnable() {
            public void run() {
                Log.i(TAG, "Where am I? " + Thread.currentThread().getName());
            }
        });
        
        // to send a message
        int what = 0; // define your own values
        int arg1 = 1;
        int arg2 = 2;
        Message msg = Message.obtain(handler, what, arg1, arg2);
        handler.sendMessage(msg);

你可能感兴趣的:(HandlerThread的使用)