深入理解Handler机制

说到Handler机制,我们就不得不说下Android里面重要的线程:主线程(UI线程)。主线程的作用就是控制应用程序中界面的显示,更新和控件交互。当应用程序启动后,主线程就跟着启动了,所以在MainActivity的OnCreate函数中,我们可以用以下三条语句来打印出主线程的Id.

        @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
				
		Log.e("MainActivity-Thread", Thread.currentThread().getId()+"");
		Log.e("MainActivity-Thread", Looper.getMainLooper().getThread().getId()+"");
		Log.e("MainActivity-Thread", Looper.myLooper().getThread().getId()+"");
        }

对于主线程有两点需要注意的地方:

1.不要阻塞主线程,由于主线程是负责应用程序界面的显示,更新和控件交互的,所以如果我们在主线程执行一些比较耗时的操作(如网络请求等),超过5秒钟的话,界面就会出现黑屏,并弹出对话框让用户选择等待,还是关闭应用程序。所以第一点就是不要在主线程中做耗时操作,既不要阻塞主线程,把耗时操作放到子线程中去。

2.主线程是线程不安全的,所以对于UI界面的操作,一定要在主线程中进行,比如如果想在子线程中修改一个textView的Text,将会报以下错误:

Only the original thread that created a view hierarchy can touch its views

我们也可以用下面的方式来更新UI

               MainActivity.this.runOnUiThread(new Runnable(){});
                button.post(new Runnable(){});
		


由于上面的解决方式比较晦涩,而我们平时在写程序时习惯用Handler,下面就简要介绍一下Handler的使用。

Handler实现原理中比较重要的就是Looper和MessageQueue。

一个标准的使用例子如下所示:

                                Looper.prepare();
				private Handler handler = new Handler(){

					@Override
					public void handleMessage(Message msg) {
						Toast.makeText(getApplicationContext(), "handler", Toast.LENGTH_LONG).show();
					}
					
				};
				Looper.loop();
Looper.prepare()的作用其实就是生成一个新的Looper并把她放入ThreadLocal中去,关于ThreadLocal,并不是她的字面意思是一个线程,她的作用是给每一个线程维护一个变量的副本,说白了就是每个线程有一个MAP,然后变量放入MAP中,线程之间互不干扰,所以ThreadLocal并不是用来解决多线程共享变量问题,也不是用来线程同步的。
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));
    }


Looper.loop()的作用就是循环把MessageQueue里面的值拿出来,并调用msg.target.dispatchMessage方法(msg.target是一个handler),把msg传到handler,并调用handleMessage方法进行处理

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycle();
        }
    }

那有人肯定有疑问我们平时使用Handler的时候怎么没有调用Looper.prepare()和Looper.loop()方法,那是因为在程序启动的时候,在ActivityThread里面已经调用过该方法,所以用户在主线程中可以直接使用定义的handler.

public final class ActivityThread {
	......

	public static final void main(String[] args) {
		......

		Looper.prepareMainLooper();

		......

		ActivityThread thread = new ActivityThread();
		thread.attach(false);
		
		......

		Looper.loop();

		......

		thread.detach();

		......
	}
}


大家可以试一下new 一个Thread,然后在Thread的Run方法里面新建一个handler,大家就会发现系统会报下面的错误:

Can't create handler inside thread that has not called Looper.prepare() 

这是因为在Handler的构造函数中,首先会检查Looper是否为空,如果为空则会抛出上面的错误

 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;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值