您的位置:首页 > 其它

HandlerThread的使用

2014-03-07 09:57 141 查看



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
参考其他人资料:/article/2784803.html
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: