HandlerThread的使用

本文详细介绍了HandlerThread的使用方式,包括其构造、启动、Looper的初始化以及如何在内部创建Handler类。通过示例代码展示了如何在实际项目中运用HandlerThread,包括发送消息和异步任务的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()方法必须被调用。

 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值