Currently I need my application to perform an action after 5 minutes, in my case close the session, in my emulators and my physical phone is 10 but on some phones it does not work, I am not sure if the battery saving could make it not count time with CountDownTimer or that could make the time not decrease, I need the time to count even if the screen is locked or in the background I currently use
public class MyCountDownTimer extends CountDownTimer {
Context context = null;
public MyCountDownTimer(long startTime, long interval,Context context) {
super(startTime, interval);
this.context = context;
}
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
Intent intent = new Intent(context, Login.class);
Toast.makeText(context, context.getString(R.string.SessionExpirada),Toast.LENGTH_LONG).show();
context.startActivity(intent);
}
}
Then I have another method that restarts when the person interacts
@Override
public void onUserInteraction(){
super.onUserInteraction();
if(!Globals.getContadorSalidaON()){
countDownTimer.cancel();
countDownTimer.start();
}
}
For what this works for me in some and in others it simply does not work, I could use another component that meets my requirements or I could fix the CountDownTimer so that it always works even in the background and in battery saving
This answer does not answer how to implement a timer that triggers a logoff, but rather how to "close" a local session by measuring the elapsed time and comparing it against a predefined limit.
The solution is to store a value
long
with the time returned forSystem.currentTimeMillis()
each time the app is interacted with, and compare this value against the previous one to determine if more than the time limit has elapsed.The comparison is achieved by making the difference
horaInteraccionActual - horaUltimaInteracción
. The result of the difference is milliseconds so to take it to minutes you have to divide by 60000.To preserve the value of the last iteration we can persist it in
SharedPreferences
. This variable can be read inonResume()
and stored inonPause()
.The solution is simple compared to alternatives that involve using a service with CountdownTimer, or using the AlarmManager. And from a practical point of view, what is obtained as a result is very similar: After a certain time has elapsed, the user cannot use the app without authenticating .
The difference is that you cannot be notified of the logoff at the time (5 minutes in the question), and if any logoff work needs to be done, it is delayed until the next user interaction. (Although this is debatable since a solution with AlarmManager may be subject to delay as well.)
The activity: