对于Handler的构造函数,looper的功能是什么?

时间:2018-01-31 10:48:42

标签: android android-handler android-looper

我对LooperHandler的功能感到困惑。

我有一些像这样的代码:

snippet1:

mThread = new Thread(){
    @Override
    public void run() {
        Log.d(tag, "thread 1 current thread:" + Thread.currentThread());
        //if(null == Looper.myLooper()) {// This is redundant.
            //Looper.prepare();
        //}
        Log.d(tag, "thread 2 current thread:" + Thread.currentThread());
        mHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                Log.d(tag, "thread 3 current thread:" + Thread.currentThread());
            }
        };
        mHandler.sendEmptyMessage(0);
        //Looper.loop(); // This is redundant since mHandler has a mainLooper, and loop in main thread.
    }
};

snippet2:

mThread = new Thread(){
    @Override
    public void run() {
        Log.d(tag, "thread 1 current thread:" + Thread.currentThread());
        if(null == Looper.myLooper()) {
            Looper.prepare();
        }
        Log.d(tag, "thread 2 current thread:" + Thread.currentThread());
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.d(tag, "thread 3 current thread:" + Thread.currentThread());
            }
        };
        mHandler.sendEmptyMessage(0);
        Looper.loop();
    }
};

将不同的Looper传递给Handler,我从handleMessage获得了不同的输出, snippet1 log" 3"输出主线程,snippet2 log"线程3"输出子线程,所以我对Looper传递给Handler的函数感到困惑,可以切换线程在哪里处理方法handlerMessage 。我还没有找到Handler来源的任何线索。

任何人都可以帮助我,提前谢谢。

0 个答案:

没有答案