我有一个 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())
实例化 Handler
和 getWindow().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/