- Handler
Handler的运行机制:Android的消息处理机制
单链表的方式Message Queue
Looper 无限循环去查询,处理消息
ThreadLocal 在各个线程中自由存取数据
Handler 是如何获取到当前线程的looper的? ThreadLocal可以轻松的获取各个线程的Looper,需要注意的是:线程默认是没有Looper的,如果某个线程需要使用Handler就必须为这个线程创建Looper。我们提到的主线程也就是UI线程,他的名字是Activity Thread,由于它在创建时,就会自动创建Looper,所以在主线程中,不同去管它的Looper的创建,而直接使用Handler。
Handler的主要作用是将一个任务切换到某个具体的线程中去执行 。
原理:Handler在创建时候会采用当前线程的Looper来构建内部的消息循环系统,如果当前没有Looper就会报错。解决的方法就是为当前线程创建Looper,对于已经创建了Looper的线程,Handler可以直接创建。
在成功new Handler之后,就可以使用了:
通过Handler的send/post方法将一个Runnable投递到本线程Handler/Looper中去处理。当send方法被调用之后,MessageQueue的enqueueMessage的方法将本条消息放置到消息队列当中,轮寻的Looper发现有消息过来了,就会去处理这个消息:Runnable 就会被调用,或者 handleMessage方法被调同。这样子线程中send出来的业务逻辑被传递到,创建Handler所在的主线程中去了。
Demo:如何在子线程中创建Handler (注意Looper的创建)
- Drawable
Drawable 就是整套的画图工具,包括Paint画笔,canvas画布,Bitmap成果图,view就是一个容器,是工具箱,通过 getDrawable()可以拿出Drawable来,如果有的话。
/**- Gets the current Drawable, or null if no Drawable has been
- assigned.
- @return the view’s drawable, or null if no drawable has been
- assigned.
*/
public Drawable getDrawable() {
if (mDrawable == mRecycleableBitmapDrawable) {
// Consider our cached version dirty since app code now has a reference to it
mRecycleableBitmapDrawable = null;
}
return mDrawable;
}
拿到了这个Drawable之后,就可以开始画画了。画出的效果bitmap,可以通过imageView加以展示。
ImageView对象.setImageBitmap(Bitmap)。这里的Bitmap对象也可以通过将正常的图片bitmap化:
Bitmap.xxFactorydecode…(…。
–写一个blog(网络日志)–