前言:基于Android 31阅读源码 @Deprecated
1:Handler的常见用法:
1.1:主线程实现方式
/**
* 定义静态内部类实现Handler
* 从Android 11 起,Handler 被标注为:@Deprecated
*/
class MyStaticHandler(activity: HandlerActivity) : Handler() {
private var weakReference: WeakReference<HandlerActivity>? = null
init {
weakReference = WeakReference(activity)
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
weakReference?.get()?.let {
Log.e(it.TAG, "handleMessage: what: ${msg.what}")
}
}
}
//调用实现发送消息:
//主线程发送消息
val myHandle: MyStaticHandler = MyStaticHandler(this@HandlerActivity)
val message = myHandle.obtainMessage(11)
myHandle.sendMessage(message)
1.2:协程内实现方式
var threadHandler: Handler? = null
//协程内Handler接收处理消息
CoroutineScope(Dispatchers.Default).launch {
Looper.prepare()
threadHandler = @SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
Log.e(TAG, "handleMessage: .what==${msg.what} in Thread.name:${Thread.currentThread().name}")
Looper.myLooper()?.quitSafely()//消息处理完成后,退出Looper 不在堵塞子线程,释放
}
}
Looper.loop()
}
//协程内发送消息
CoroutineScope(Dispatchers.Default).launch {
threadHandler?.sendEmptyMessage(55)
}
2、Handler发送消息的几种方式,主要是 send 和 post 的api上
//主线程发送消息
val myHandle: MyStaticHandler = MyStaticHandler(this@HandlerActivity)
val message = myHandle.obtainMessage(11)
myHandle.sendMessage(message)
myHandle.sendMessage(Message().apply { what = 22 })
myHandle.sendEmptyMessage(33)
myHandle.sendEmptyMessageDelayed(44,3000)
myHandle.sendMessageAtFrontOfQueue(Message().apply { what = 55 })
myHandle.post {
Log.e(TAG, "callback-run: ", )
}
//等等其它几个api
3、Handler 三要素:Looper、Message、MessageQueue
3.1:Looper:
实例化 Handler 的时候 Handler 会去检查当前线程的 Looper 是否存在,如果不存在则会报异常,也就是说在创建 Handler 之前一定需要先创建 Looper 。源码如下
public Handler(@Nullable Callback callback, boolean async) {
if (FIND