zoukankan      html  css  js  c++  java
  • 【转】Android中removeCallbacks失效原因

    原文网址:http://blog.sina.com.cn/s/blog_6714fba70100wtx1.html

    在Android开发中会使用Handle的removeCallbacks函数,该函数功能为:

    image

    但实际工作中有时会出现removeCallbacks无效,解决它。

    图:两个按钮,一个将Runnable加到消息队列中,一个将Runnable从消息队列中移除。该Runnable每3秒钟打印一次日志。

    image

    SNAGHTML97e957[4]

    码:

    image

    结果:

    (1)start –>  输出 –> end –> 停止输出

    (2)start –> 输出 –>  BackGround –> Front –> 继续输出

    当Activity进入后台运行后再转入前台运行,removeCallbacks无法将updateThread从message queue中移除。

    这是为什么呢?

    在Activity由前台转后台过程中,线程是一直在运行的,但是当Activity转入前台时会重新定义Runnable updateThread;也就是说此时从message queue移除的updateThread与原先加入message queue中的updateThread并非是同一个对象。如果把updateThread定义为静态的则removeCallbacks不会失效,如图:

    image

    此时,post,postDelayed,removeCallback面对的是同一个handler,updateThread,因此能够实现remove。

    这个原因即使是正确的也是表面原因,具体原因需要深入底层机制去了解,求解中。。。

  • 相关阅读:
    Leetcode Plus One
    Leetcode Swap Nodes in Pairs
    Leetcode Remove Nth Node From End of List
    leetcode Remove Duplicates from Sorted Array
    leetcode Remove Element
    leetcode Container With Most Water
    leetcode String to Integer (atoi)
    leetcode Palindrome Number
    leetcode Roman to Integer
    leetcode ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/wi100sh/p/5586353.html
Copyright © 2011-2022 走看看