Auto logout after 15 minutes due to inactivity in android

百般思念 提交于 2019-12-03 08:50:58

Use CountDownTimer

CountDownTimer timer = new CountDownTimer(15 *60 * 1000, 1000) {

        public void onTick(long millisUntilFinished) {
           //Some code
        }

        public void onFinish() {
           //Logout
        }
     };

When user has stopped any action use timer.start() and when user does the action do timer.cancel()

user1398739

I am agree with Girish in above answer. Rash for your convenience i am sharing code with you.

public class LogoutService extends Service {
        public static CountDownTimer timer;
    @Override
    public void onCreate(){
        super.onCreate();
          timer = new CountDownTimer(1 *60 * 1000, 1000) {
                public void onTick(long millisUntilFinished) {
                   //Some code
                    Log.v(Constants.TAG, "Service Started");
                }

                public void onFinish() {
                    Log.v(Constants.TAG, "Call Logout by Service");
                    // Code for Logout
                    stopSelf();
                }
             };
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Add the following code in every activity.

    @Override
protected void onResume() {
    super.onResume();

    LogoutService.timer.start();
}

@Override
protected void onStop() {
    super.onStop();
    LogoutService.timer.cancel();
}   

You can start a service and start a timer in it. Every 15 minutes, check if a flag, let's say inactivity flag is set to true. If it is, logout form the app.

Every time the user interacts with your app, set the inactivity flag to false.

you may need to create a BaseActivity class which all the other Activities in your app extend. in that class start your timer task (TimerTask()) in the onUserInteraction method:

override fun onUserInteraction() {
    super.onUserInteraction()
    onUserInteracted()
}

. The onUserInteracted class starts a TimerTaskService which will be an inner class for my case as below:

private fun onUserInteracted() {
     timer?.schedule(TimerTaskService(), 10000)
}

The TimerTaskService class will be asfollows. Please note the run on UI thread in the case you want to display a DialogFragment for an action to be done before login the user out:

inner class TimerTaskService : TimerTask() {
    override fun run() {
        /**This will only run when application is in background
         * it allows the application process to get high priority for the user to take action
         * on the application auto Logout
         * */
//            val activityManager = applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//            activityManager.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_NO_USER_ACTION)

        runOnUiThread {
            displayFragment(AutoLogoutDialogFragment())
            isSessionExpired = true
        }
        stopLoginTimer()
    }
}

You will realise i have a stopTimer method which you have to call after the intended action has be envoked, this class just has timer?.cancel() and you may also need to include it in the onStop() method.

NB: this will run in 10 seconds because of the 10000ms

I hope this will help

I found it on github https://gist.github.com/dseerapu/b768728b3b4ccf282c7806a3745d0347

public class LogOutTimerUtil {

 public interface LogOutListener {
  void doLogout();
 }

 static Timer longTimer;
 static final int LOGOUT_TIME = 600000; // delay in milliseconds i.e. 5 min = 300000 ms or use timeout argument

 public static synchronized void startLogoutTimer(final Context context, final LogOutListener logOutListener) {
  if (longTimer != null) {
   longTimer.cancel();
   longTimer = null;
  }
  if (longTimer == null) {

   longTimer = new Timer();

   longTimer.schedule(new TimerTask() {

    public void run() {

     cancel();

     longTimer = null;

     try {
      boolean foreGround = new ForegroundCheckTask().execute(context).get();

      if (foreGround) {
       logOutListener.doLogout();
      }

     } catch (InterruptedException e) {
      e.printStackTrace();
     } catch (ExecutionException e) {
      e.printStackTrace();
     }

    }
   }, LOGOUT_TIME);
  }
 }

 public static synchronized void stopLogoutTimer() {
  if (longTimer != null) {
   longTimer.cancel();
   longTimer = null;
  }
 }

 static class ForegroundCheckTask extends AsyncTask < Context, Void, Boolean > {

  @Override
  protected Boolean doInBackground(Context...params) {
   final Context context = params[0].getApplicationContext();
   return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
   ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   List < ActivityManager.RunningAppProcessInfo > appProcesses = activityManager.getRunningAppProcesses();
   if (appProcesses == null) {
    return false;
   }
   final String packageName = context.getPackageName();
   for (ActivityManager.RunningAppProcessInfo appProcess: appProcesses) {
    if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
     return true;
    }
   }
   return false;
  }
 }

}

Use above code in Activity as below :

public class MainActivity extends AppCompatActivity implements LogOutTimerUtil.LogOutListener
{
    @Override
    protected void onStart() {
        super.onStart();
        LogOutTimerUtil.startLogoutTimer(this, this);
        Log.e(TAG, "OnStart () &&& Starting timer");
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        LogOutTimerUtil.startLogoutTimer(this, this);
        Log.e(TAG, "User interacting with screen");
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause()");
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.e(TAG, "onResume()");
    }

    /**
     * Performing idle time logout
     */
    @Override
    public void doLogout() {
      // write your stuff here
    }
}

Make use of Handler, UserInteraction() and Runnable class.

CODE: MainActivity.java

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
           // manageBackup(true,false);
            logout();
        }
    };

    startHandler(); //will start the timer. This must be withing onCreate() scope.

//Code for Inactivity part.

       @Override
public void onUserInteraction() {
    super.onUserInteraction();
    stopHandler();  //first stop the timer and then again start it
    startHandler();
}

public void stopHandler() {
    handler.removeCallbacks(runnable);
}
public void startHandler() {
    handler.postDelayed(runnable, 15*60*1000); //for 15 minutes
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!