Android面试常客之Handler全解1

简介: Android面试常客之Handler全解

前言:又到了一年一度的跳槽季,准备跳槽的你在关于Android面试方面的知识都完全掌握了吗?Android面试中经常被问到的知识——Android消息机制即Handler有关的问题你都能解释的清楚吗?如果你对Android消息机制比较模糊或者能够回答与Handler有关的问题但是不清楚其中的原理,那么你将会在本文得到你想要的答案。

阅读本文后的收货

  阅读本文后你将会有以下收获:

  • 清楚的理解Handler的工作原理
  • 理清Handler、Message、MessageQueue以及Looper之间的关系
  • 知道Looper是怎么和当前线程进行绑定的
  • 是否能在子线程中创建Handler
  • 获得分析Handler源码的思路

要想有以上的收获,就需要研究Handler的源码,从源码中来得到答案。

开始探索之路

Handler的使用

  先从Handler的使用开始。我们都知道Android的主线程不能处理耗时的任务,否者会导致ANR的出现,但是界面的更新又必须要在主线程中进行,这样,我们就必须在子线程中处理耗时的任务,然后在主线程中更新UI。但是,我们怎么知道子线程中的任务何时完成,又应该什么时候更新UI,又更新什么内容呢?为了解决这个问题,Android为我们提供了一个消息机制即Handler。下面就看下Handler的常见使用方式,代码如下

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mStartTask;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(MainActivity.this, "刷新UI、", Toast.LENGTH_SHORT).show();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        mStartTask = findViewById(R.id.btn_start_task);
        mStartTask.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_task:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                            mHandler.sendEmptyMessage(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
        }
    }
}

可以看到在子线程中,让线程睡了一秒,来模仿耗时的任务,当耗时任务处理完之后,Handler会发送一个消息,然后我们可以在Handler的handleMessage方法中得到这个消息,得到消息之后就能够在handleMessage方法中更新UI了,因为handleMessage是在主线程中嘛。到这里就会有以下疑问了:

  • Handler明明是在子线程中发的消息怎么会跑到主线程中了呢?
  • Handler的发送消息handleMessage又是怎么接收到的呢?

带着这两个疑问,开始分析Handler的源码。

Handler的源码分析

  先看下在我们实例化Handler的时候,Handler的构造方法中都做了那些事情,看代码

  final Looper mLooper;
    final MessageQueue mQueue;
    final Callback mCallback;
    final boolean mAsynchronous;
/**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }
/**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    public Handler(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 that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通过源码可以看到Handler的无参构造函数调用了两个参数的构造函数,而在两个参数的构造函数中就是将一些变量进行赋值。

  看下下面的代码

 mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }

这里是通过Looper中的myLooper方法来获得Looper实例的,如果Looper为null的话就会抛异常,抛出的异常内容翻译过来就是

无法在未调用Looper.prepare()的线程内创建handler

从这句话中,我们可以知道,在调用Looper.myLooper()之前必须要先调用Looper.prepare()方法,现在来看下prepare方法中的内容,如下

 /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

从上面代码中可以看到,prepare()方法调用了prepare(boolean quitAllowed)方法,prepare(boolean quitAllowed) 方法中则是实例化了一个Looper,然后将Looper设置进sThreadLocal中,到了这里就有必要了解一下ThreadLocalle。

什么是ThreadLocal

ThreadLocal 为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序。当使用ThreadLocal 维护变量时,ThreadLocal 为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

如果看完上面这段话还是搞不明白ThreadLocal有什么用,那么可以看下下面代码运行的结果,相信看下结果你就会明白ThreadLocal有什么作用了。

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private ThreadLocal<Integer> mThreadLocal = new ThreadLocal<>();
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Log.d(TAG, "onCreate: "+mThreadLocal.get());
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mThreadLocal.set(5);
        Thread1 thread1 = new Thread1();
        thread1.start();
        Thread2 thread2 = new Thread2();
        thread2.start();
        Thread3 thread3 = new Thread3();
        thread3.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    mHandler.sendEmptyMessage(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    class Thread1 extends Thread {
        @Override
        public void run() {
            super.run();
            mThreadLocal.set(1);
            Log.d(TAG, "mThreadLocal1: "+ mThreadLocal.get());
        }
    }
    class Thread2 extends Thread {
        @Override
        public void run() {
            super.run();
            mThreadLocal.set(2);
            Log.d(TAG, "mThreadLocal2: "+ mThreadLocal.get());
        }
    }
    class Thread3 extends Thread {
        @Override
        public void run() {
            super.run();
            mThreadLocal.set(3);
            Log.d(TAG, "mThreadLocal3: "+ mThreadLocal.get());
        }
    }
}

看下这段代码运行之后打印的log

可以看到虽然在不同的线程中对同一个mThreadLocal中的值进行了更改,但最后仍可以正确拿到当前线程中mThreadLocal中的值。由此我们可以得出结论ThreadLocal.set方法设置的值是与当前线程进行绑定了的。

  知道了ThreadLocal.set方法的作用,则Looper.prepare方法就是将Looper与当前线程进行绑定(当前线程就是调用Looper.prepare方法的线程)

  文章到了这里我们可以知道以下几点信息了

  • 在对Handler进行实例化的时候,会对一些变量进行赋值。
  • 对Looper进行赋值是通过Looper.myLooper方法,但在调用这句代码之前必须已经调用了Looper.prepare方法。
  • Looper.prepare方法的作用就是将实例化的Looper与当前的线程进行绑定。

这里就又出现了一个问题:在调用Looper.myLooper方法之前必须必须已经调用了Looper.prepare方法,即在实例化Handler之前就要调用Looper.prepare方法,但是我们平常在主线程中使用Handler的时候并没有调用Looper.prepare方法呀!这是怎么回事呢?

  其实,在主线程中Android系统已经帮我们调用了Looper.prepare方法,可以看下ActivityThread类中的main方法,代码如下

 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);
        Environment.initForCurrentUser();
        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());
        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

上面的代码中有一句

Looper.prepareMainLooper();
这句话的实质就是调用了Looper的prepare方法,代码如下
csharp
复制代码
 public static void prepareMainLooper() {
        prepare(false);//这里调用了prepare方法
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

到这里就解决了,为什么我们在主线程中使用Handler之前没有调用Looper.prepare方法的问题了。

  让我们再回到Handler的构造方法中,看下

mLooper = Looper.myLooper();

myLooper()方法中代码如下

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

其实就是从当前线程中的ThreadLocal中取出Looper实例。

  再看下Handler的构造方法中的

mQueue = mLooper.mQueue;

这句代码。这句代码就是拿到Looper中的mQueue这个成员变量,然后再赋值给Handler中的mQueue,下面看下Looper中的代码

 final MessageQueue mQueue;
  private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

同过上面的代码,我们可以知道mQueue就是MessageQueue,在我们调用Looper.prepare方法时就将mQueue实例化了。


相关文章
|
3月前
|
安全 Android开发 开发者
【Android开发小技巧】扔掉这坑人的 Handler
【Android开发小技巧】扔掉这坑人的 Handler
40 0
|
7月前
|
XML Java Android开发
Android面试官最喜欢问15道面试题
Android面试官最喜欢问15道面试题
93 0
|
7月前
|
存储 SQL 安全
Android面试中问的线程相关问题
Android面试中问的线程相关问题
40 0
|
1月前
|
存储 SQL 关系型数据库
索引和事务究竟是何方神圣?那可是面试中的常客!
索引和事务究竟是何方神圣?那可是面试中的常客!
43 1
索引和事务究竟是何方神圣?那可是面试中的常客!
|
1月前
|
存储 安全 Java
Android 面试题及答案整理,最新面试题
Android 面试题及答案整理,最新面试题
93 2
|
7月前
|
程序员 数据库 Android开发
面试问你Android中Context,你如何回答?
面试问你Android中Context,你如何回答?
65 0
|
4月前
|
消息中间件 缓存 安全
android开发,使用kotlin学习消息机制Handler
android开发,使用kotlin学习消息机制Handler
84 0
|
7月前
|
SQL Java Linux
Android面试问题收集
Android面试问题收集
75 1
|
7月前
|
算法 网络协议 Java
Android面试知识点复习手册(收藏)
Android面试知识点复习手册(收藏)
85 0
|
29天前
|
Java 程序员
java线程池讲解面试
java线程池讲解面试
52 1