Android HandlerThread

1.  什么是HandlerThread?
A Thread that has a Looper. The Looper can then be used to create Handlers.
Note that just like with a regular Thread, start() must still be called.

        handlerThread本质上是一个线程类,继承了Thread;

        他就是在一个子线程内部创建并管理一个Looper;

2.  为什么使用HandlerThread?

        自带Looper消息循环;可以快速创建一个带有Looper的线程,更加方便、便捷;

3.  怎么使用HanderThread?

        注:创建HandlerThread后必须先调用start()方法,其会先调用run()方法,创建Looper对象;

        Button handlerThreadBt = findViewById(R.id.main_handler_thread_bt);
        Context context = getApplicationContext();
        Thread thread = new Thread(() -> {
            // 1、创建HandlerThread对象
            HandlerThread handlerThread = new HandlerThread("myToast");

            // 2、必须先开启HandlerThread线程
            handlerThread.start();

            // 3、构建子线程Handler
            Handler handler = new Handler(handlerThread.getLooper(), msg -> {
                if (msg.what == 1) {
                    Toast toast = Toast.makeText(context, getText(R.string.handler_thread_toast), Toast.LENGTH_LONG);
                    toast.show();

                    return true;
                }
                return false;
            });

            // 4、在子线程发送消息,更新UI
            handlerThreadBt.setOnClickListener(v -> {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            });
        });
        thread.start();

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值