AKh AKh - 1 year ago 364
Android Question

How to detect USER INACTIVITY in android

User start MyAPP 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

My Question:

I want this 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.

Thanks in advance.

Answer Source
MyApplciation extents Application(){
  private int lastInteraction;
  private Boolean isScreenOff = false; 
  public void onCreate(){
  startUserInactivityDetectThread(); // start the thread to detect inactivity
     new ScreenReceiver();  // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device.

  public void startUserInactivityDetectThread(){
    new Thread(new Runnable() {
       public void run() {
         while(true) {
            Thread.sleep(15000); // checks every 15sec for inactivity
              if(isScreenOff || getLastInteractionTime > 120000 ||  !isInForeGrnd)
                //...... means USER has been INACTIVE over a period of
                // and you do your stuff like log the user out 

    public long getLastInteractionTime() {
       return lastInteractionTime;

    public long setLastInteractionTime(int lastInteraction) {
       lastInteractionTime = lastInteraction;

    private class ScreenReceiver extends BroadcastReceiver {

    protected ScreenReceiver() {
       // register receiver that handles screen on and screen off logic
       IntentFilter filter = new IntentFilter();
       registerReceiver(this, filter);

    public void onReceive(Context context, Intent intent) {
       if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
         isScreenOff = true;
       } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
           isScreenOff = false;

isInForeGrnd ===> logic is not shown here as it is out of scope of the question