Reputation: 3080
I have a Android application that verifies the user inactivity through a Handler
. But I would like know if my Handler
implementation is the best solution in my case.
The code:
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!");
}
}
}
}
My main questions are:
1) What is the difference between instantiate Handler
using new Handler(Looper.getMainLooper())
and getWindow().getDecorView().getHandler()
?
2) The use of System.currentTimeMillis()
in this context is secure?
Upvotes: 3
Views: 572
Reputation: 134664
1) As @corsair992 said, they should be equivalent, however I think having your own instance of Handler
is preferable, as you explicitly control it. If you need to remove any pending Runnable
instances later, you can just do a removeCallbacksAndRunnables(null);
to remove any messages that your Handler
has posted without affecting the decor view's Handler
.
2) Don't use System.currentTimeMillis()
. SystemClock.elapsedRealtime()
is a much better indicator of elapsed time, as it won't be affected by the user changing the Date/Time (whereas currentTimeMillis()
does change).
Upvotes: 3