欢迎来到天天文库
浏览记录
ID:6379978
大小:296.00 KB
页数:36页
时间:2018-01-12
《android消息处理机制》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、Android消息处理机制(Handler、Looper、MessageQueue与Message)Android是消息驱动的,实现消息驱动有几个要素:1.消息的表示:Message2.消息队列:MessageQueue3.消息循环,用于循环取出消息进行处理:Looper4.消息处理,消息循环从消息队列中取出消息后要对消息进行处理:Handler平时我们最常使用的就是Message与Handler了,如果使用过HandlerThread或者自己实现类似HandlerThread的东西可能还会接触到Looper,而MessageQueue是Looper内部使用的,对于
2、标准的SDK,我们是无法实例化并使用的(构造函数是包可见性)。我们平时接触到的Looper、Message、Handler都是用JAVA实现的,Android做为基于Linux的系统,底层用C、C++实现的,而且还有NDK的存在,消息驱动的模型怎么可能只存在于JAVA层,实际上,在Native层存在与Java层对应的类如Looper、MessageQueue等。 初始化消息队列首先来看一下如果一个线程想实现消息循环应该怎么做,以HandlerThread为例:publicvoidrun(){mTid=Process.myTid();Looper.prepare();
3、synchronized(this){mLooper=Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid=-1;} 主要是红色标明的两句,首先调用prepare初始化MessageQueue与Looper,然后调用loop进入消息循环。先看一下Looper.prepare。publicstaticvoidprepare(){prepare(true);}privatestaticvoidprepare(boo
4、leanquitAllowed){if(sThreadLocal.get()!=null){thrownewRuntimeException("OnlyoneLoopermaybecreatedperthread");}sThreadLocal.set(newLooper(quitAllowed));}重载函数,quitAllowed默认为true,从名字可以看出来就是消息循环是否可以退出,默认是可退出的,Main线程(UI线程)初始化消息循环时会调用prepareMainLooper,传进去的是false。使用了ThreadLocal,每个线程可以初始化一个Loo
5、per。再来看一下Looper在初始化时都做了什么:privateLooper(booleanquitAllowed){mQueue=newMessageQueue(quitAllowed);mRun=true;mThread=Thread.currentThread();}MessageQueue(booleanquitAllowed){mQuitAllowed=quitAllowed;nativeInit();} 在Looper初始化时,新建了一个MessageQueue的对象保存了在成员mQueue中。MessageQueue的构造函数是包可见性,所以我们是无
6、法直接使用的,在MessageQueue初始化的时候调用了nativeInit,这是一个Native方法:staticvoidandroid_os_MessageQueue_nativeInit(JNIEnv*env,jobjectobj){NativeMessageQueue*nativeMessageQueue=newNativeMessageQueue();if(!nativeMessageQueue){jniThrowRuntimeException(env,"Unabletoallocatenativequeue");return;}nativeMessa
7、geQueue->incStrong(env);android_os_MessageQueue_setNativeMessageQueue(env,obj,nativeMessageQueue);}staticvoidandroid_os_MessageQueue_setNativeMessageQueue(JNIEnv*env,jobjectmessageQueueObj,NativeMessageQueue*nativeMessageQueue){env->SetIntField(messageQueueObj,gMessageQueueClassInfo.
此文档下载收益归作者所有