java - 与 UI 线程通信 Android : User Inactivity

标签 java android multithreading performance android-handler

我有一个 Android 应用程序,它通过 Handler 验证用户是否处于 Activity 状态。但我想知道我的 Handler 实现是否是我的最佳解决方案。

代码:

public abstract class UserInteractionControlActivity extends Activity {

    private static final int SESSION_TIME_OUT = 300000;
    private static final int SESSION_DELAY_TIME = 60000;

    private final Handler mHandler = new Handler(Looper.getMainLooper());

    private long mLastUserInterationTime;

    protected void onResume() {
        super.onResume();
        mHandler.postDelayed(new UserInteractionControl(), SESSION_TIME_OUT);
        Log.i("LOG_KEY", "HANDLER FIRST POST!");
    }

    public void onUserInteraction() {
        super.onUserInteraction();
        mLastUserInterationTime = System.currentTimeMillis();
    }

    private final class UserInteractionControl implements Runnable {

        public void run() {
            long currentTime = System.currentTimeMillis();
            long inactiveTime = currentTime - mLastUserInterationTime;
            if (inactiveTime > SESSION_TIME_OUT) {
                Log.i("LOG_KEY", "TIME OUT!");
            } else {
                mHandler.postDelayed(new UserInteractionControl(), SESSION_DELAY_TIME);
                Log.i("LOG_KEY", "HANDLER POST AGAIN!");
            }
        }
    }
}

我的主要问题是:

1) 使用 new Handler(Looper.getMainLooper()) 实例化 HandlergetWindow().getDecorView().getHandler( )?

2) 在此上下文中使用 System.currentTimeMillis() 是否安全?

最佳答案

1) 正如@corsair992 所说,它们应该是等效的,但是我认为拥有自己的 Handler 实例更好,因为您可以明确控制它。如果您以后需要删除任何挂起的 Runnable 实例,您只需执行 removeCallbacksAndRunnables(null); 即可删除您的 Handler 拥有的任何消息在不影响装饰 View 的 Handler 的情况下发布。

2) 不要使用 System.currentTimeMillis()SystemClock.elapsedRealtime() 是耗时的更好指示器,因为它不会受到用户更改日期/时间的影响(而 currentTimeMillis() 确实改变了)。

关于java - 与 UI 线程通信 Android : User Inactivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27968289/

相关文章:

java - 在 JFrame 中重新加载 GUI 出现问题

Java:展开JButton填充Container

c++ - SQLite 数据库被锁定

用 C 语言为 IRC 机器人创建一个基本 shell,并在后台运行另一个线程

c++ - 可移植的 C++ 单例 - 何时调用析构函数

java - 使用数组和可变长度形式参数。 (java :38: error: '.class' expected)

java - 如何在构建时在Gradle中运行控制台命令?

android - 如何检测文件修改?

android - 如何通过知道元素 id 滚动到 ScrollView 中的特定 View 元素

java - Android Firebase 数据库不断更新值(value)