Search code examples
androidtimercountdowntimer

Auto logout after 15 minutes due to inactivity in android


How to use timer in android for auto logout after 15 minutes due to inactivity of user?

I am using bellow code for this in my loginActivity.java

public class BackgroundProcessingService extends Service {

        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
         timer = new CountDownTimer(5 *60 * 1000, 1000) {

                public void onTick(long millisUntilFinished) {
                   //Some code
                    //inactivity = true;
                    timer.start();
                    Log.v("Timer::", "Started");
                }

                public void onFinish() {
                   //Logout
                    Intent intent = new Intent(LoginActivity.this,HomePageActivity.class);
                    startActivity(intent);
                    //inactivity = false;
                    timer.cancel();
                    Log.v("Timer::", "Stoped");
                }
             };
            return null;
        }

    }

and onclick of login button I have called intent for service.

Intent intent1 = new Intent(getApplicationContext(),
                        AddEditDeleteActivity.class);
                startService(intent1);

Please advice......

This type of error message is shown after 15 mins

This type of error message is shown after 15 mins


Solution

  • 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()