【子线程创建handler】

子线程创建handler

子线程创建handler的方式,在这里做个记录

Thread(object : Runnable {
    override fun run() {
        Looper.prepare()
        //Looper.myLooper()这里也可以不写,Handler会自动获取当前线程的looper
        //也可以用Looper.getMainLooper()获取主线程的looper
        //Looper.getMainLooper()在整个程序进程中是单例的
        //进程在ActivityThread中调用Looper.prepareMainLooper()初始化Looper.getMainLooper()
        //通过设置AndroidManifest.xml中的process,可以让产生多个进程,让Looper.getMainLooper()不一样
        val handler = Handler(Looper.myLooper())
        handler.post {
            L.i("ss ${Looper.myLooper()?.toString()}")
        }
        Looper.loop()
    }
}).start()
在这里插入代码片
private val handlerThread = HandlerThread("Controller")
handlerThread.start()
threadHandler = object :Handler(handlerThread.looper){
            override fun handleMessage(msg: Message) {
                when (msg.what){
                    0 ->{
                        Toast.makeText(MyApplication.context,"111111",Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

下面这种方面 handlerthread的run方法中会调用looper.prepare()方法 不会抛出not called Looper.prepare()异常

public Handler(@Nullable Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }