androidandroid-studiologoutandroid-timer

Android Logout timer


I have made an app. I want to automatically log out from the app after the certain time period when user exit app or app running in the background. I have created timer but it doesn't work as when the app goes in onStop() timer also becomes stop. What should I do for this problem?


Solution

  • Make all your Activities extends one BaseActivity. Then in this BaseActivity declare pausedMillis paramater :

    private long pausedMillis;
    

    After that Override the onStop method :

    @Override
    protected void onStop() {
        super.onStop();
        pausedMillis = Calendar.getInstance().getTimeInMillis();
    }
    

    In the end Override onResume method :

    @Override
    public void onResume(){
        super.onResume();
    
        try {
            long currentMillis = Calendar.getInstance().getTimeInMillis();
            if ( !(this instanceof LoginActivity) && currentMillis - pausedMillis  > 1000 * 60 * 3 ) {
                Intent intent = new Intent(this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
                Toast.makeText(BaseActivity.this, getString(R.string.logout_string), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    

    This will log out you if your app is more then 3 minutes in background. Happy codding :)