User start my app and logs in.
Selects Session Timeout to be 5 mins.
Does some operations on the app. (all in foreground)
Now User bring Myapp to background and starts some other app.
----> Count down timer starts and logs out user after 5 mins
OR user turns the screen OFF.
----> Count down timer starts and logs out user after 5 mins
I want the same behavior even when the app is in the foreground but user doesn't interact with the app for a long-time say 6-7 mins. Assume the screen is ON all the time. I want to detect kind of user inactivity (No interaction with app even though the app is in the foreground) and kick start my count down timer.
I don't know a way of tracking inactivity but there is a way to track user activity. You can catch a callback called
onUserInteraction()
in your activities that is called every time the user does any interaction with the application. I'd suggest doing something like this:If your app contains several activities, why not put this method in an abstract super class (extending
Activity
) and then have all you activities extending it.I think it needs to be by combining the timer with the last activty time.
So like this:
In onCreate(Bundle savedInstanceState) start a timer, say 5 minutes
In onUserInteraction() just store the current time
Pretty simple so far.
Now when the timer pop do like this:
I came up with a solution that I find quite simple based on Fredrik Wallenius's answer. This a base activity class that needs to be extended by all activities.
During my Search I found a lot of answers but this is the best answer I got. But limitation of this code is that it works only for activity not for whole application. Take this as a reference.
for e.g you used 8000, the task will be done after 8 seconds of user inactivity.
I had similar situation to the SO question, where i needed to track the user inactivity for 1 minute then redirect the user to start Activity, i needed also to clear the activity stack.
Based on @gfrigon answer i come up with this solution.
ActionBar.java
Complementary resources
Android: Clear Activity Stack
This Handler class should be static or leaks might occur
Best thing is to handle this across your whole app (assuming you have multiple activities) by registering
AppLifecycleCallbacks
in the Application calss. You can useregisterActivityLifecycleCallbacks()
in the Application class with the following callbacks (I recommend creating an AppLifecycleCallbacks class that extends the ActivityLifecycleCallbacks):