gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:39:46 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com