怎么知道Looper是否已经调用quit()成功?

怎么知道Looper是否已经调用quit()成功?


# 粘贴全部相关代码,切记添加代码注释(请勿截图)

inner class HandlerThread : Thread() {
private lateinit var mHandler: Handler

override fun run() {
super.run()
Looper.prepare()
createHandler()
val msg = Message.obtain()
msg.what = 1
       mHandler.sendMessage(msg)
Log.i(tag, "sendMessage: " + currentThread().name)
Looper.loop()
}

private fun createHandler() {
mHandler = @SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (msg.what == 1) {
Log.i(tag, "what 1  handleMessage: ${currentThread().name}  ${Looper.myLooper()?.thread?.isAlive}")
} else {
Log.i(tag, "what else  handleMessage: ${currentThread().name}")
}
Looper.myLooper()?.quitSafely()
Log.i(tag, "final  handleMessage: ${currentThread().name}  ${Looper.myLooper()?.isCurrentThread}")
}
}


}

}


实现了一下,用Hnadler子线程给子线程发送消息,课程说,要注意在合适的时机quitSafely(),但是要怎么才能知道Looper是否退出成功,自己试了几个Api,没效果,如上,打印都为true,想问下老师怎么看是否已经退出

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
LovelyChubby 2020-12-21 11:59:56

looper.quit不是有个返回值吗

  • 提问者 默小铭 #1
    ​/**
    * Quits the looper.
    * <p>
    * Causes the {@link #loop} method to terminate without processing any
    * more messages in the message queue.
    * </p><p>
    * Any attempt to post messages to the queue after the looper is asked to quit will fail.
    * For example, the {@link Handler#sendMessage(Message)} method will return false.
    * </p><p class="note">
    * Using this method may be unsafe because some messages may not be delivered
    * before the looper terminates. Consider using {@link #quitSafely} instead to ensure
    * that all pending work is completed in an orderly manner.
    * </p>
    *
    * @see #quitSafely
    */
    public void quit() {
    mQueue.quit(false);
    }

    /**
    * Quits the looper safely.
    * <p>
    * Causes the {@link #loop} method to terminate as soon as all remaining messages
    * in the message queue that are already due to be delivered have been handled.
    * However pending delayed messages with due times in the future will not be
    * delivered before the loop terminates.
    * </p><p>
    * Any attempt to post messages to the queue after the looper is asked to quit will fail.
    * For example, the {@link Handler#sendMessage(Message)} method will return false.
    * </p>
    */
    public void quitSafely() {
    mQueue.quit(true);
    }


    看源码,没有返回值哦

    2020-12-21 13:38:49
  • 这样啊,那你再发送个消息看有没有被执行,没被执行就说明退出了
    2020-12-21 18:43:04
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师