一、 需要用到的组件
1、HandlerThread
2、Handler
二、 用法
2.1 启动 HandlerThread
在使用前,先启动 HandlerThread, 以下代码我是写在 ViewModel 里
var handlerThread: HandlerThread?= null
var handlerBackground: MyBackgroundHandler?= null // 自己要执行的异步线程的 Handler
fun startHandlerThread() {
if (handlerThread == null) {
handlerThread = HandlerThread("test")
}
handlerThread?.start()
handlerThread?.looper?.let { looper->
handlerBackground = MyBackgroundHandler(WeakReference(this), looper)
}
|
2.2 自定义 Handler
class MyBackgroundHandler(private val weakReference: WeakReference<MyViewModel>, looper: Looper): Handler(looper) {
companion object {
// 定义消息的标记
const val MESSAGE_ID_REQUEST = 100
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
MESSAGE_ID_REQUEST-> { // 接收到的消息,在异步线程中执行方法
weakReference.get()?.let {
val params = msg.obj as List<Params>
it.doRequest(params = params)
}
}
}
}
// 在需要请求的地方调用这个方法,将要请求的消息放到 Handler 队列中
fun sendBackgroundMessage(actions:List<Params>) {
val msg = Message.obtain(this, MESSAGE_ID_REQUEST)
msg.obj = actions
sendMessage(msg)
}
}
2.3 自己的 ViewModel
class MyViewModel:ViewModel() {
fun doRequest(params:List<Params>) {
// 做具体的请求业务
}
// 请求放入队列
fun request(params:List<Params>) {
handlerBackground?.sendBackgroundMessage(actions = params)
}
}