HandlerThread

1.HandlerThread 首先它是Thread,继承自Thread

java 复制代码
public class HandlerThread extends Thread {}

2.与Thread不同的地方

在Thread的run方法里面

  • 调用Looper.prepare()创建Looper
  • 调用Looper.loop(),可循环处理消息
java 复制代码
public class HandlerThread extends Thread {
    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare(); //创建Looper
        synchronized (this) {//锁
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop(); //循环处理收到的Message
        mTid = -1;
    }
}

3.怎么使用,举个例子

java 复制代码
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

public class MyHandlerThreadExample {

    private HandlerThread handlerThread;
    private Handler handler;

    public MyHandlerThreadExample() {
        // 创建一个名为"MyHandlerThread"的新线程
        handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start(); // 启动线程

        // 在新线程上创建一个Handler
        handler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                // 在这里处理消息
                // 这个方法在 handlerThread 所在的线程上执行
                int what = msg.what;
                switch (what) {
                    case 1:
                        // 处理消息类型为1的情况
                        break;
                    // 添加其他处理不同消息类型的逻辑
                }
            }
        };
    }

    // 在主线程或其他地方发送消息到HandlerThread
    public void sendMessageToHandlerThread(int messageType) {
        Message message = handler.obtainMessage(messageType);
        handler.sendMessage(message);
    }

    // 在适当的时候停止HandlerThread
    public void stopHandlerThread() {
        handlerThread.quit();
    }
}
相关推荐
进击的cc2 分钟前
App 启动优化全家桶:别再只盯着 Application 了,热启动优化你真的做对了吗?
android·面试
彭波39643 分钟前
安卓手机端安装xapk、apkm软件!怎样安装xapk软件?安卓的apk和XAPK的区别?附教程
android·智能手机
Yang-Never2 小时前
ADB ->adb shell perfetto 抓取 trace 指令
android·开发语言·adb·android studio
2501_937189234 小时前
莫凡电视:地方台专属聚合 稳定直播播放工具
android·源码·源代码管理
耶叶6 小时前
Android 新权限申请模型(Activity Result API)
android
阿拉斯攀登6 小时前
【RK3576 安卓 JNI/NDK 系列 04】JNI 核心语法(下):字符串、数组与对象操作
android·驱动开发·rk3568·瑞芯微·rk安卓驱动·jni字符串操作
2501_915909066 小时前
不用越狱就看不到 iOS App 内部文件?使用 Keymob 查看和导出应用数据目录
android·ios·小程序·https·uni-app·iphone·webview
llxxyy卢6 小时前
web部分中等题目
android·前端
轩情吖6 小时前
MySQL之事务管理
android·后端·mysql·adb·事务·隔离性·原子性
万物得其道者成6 小时前
uni-app Android 离线打包:多环境(prod/dev)配置
android·opencv·uni-app