-2

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?

Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80
Malik
  • 3
  • 3

2 Answers2

0

You need to make a service to logout and use AlarmManager with the PendingIntent for that Service to launch after certain time period. Here's an example code:

AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent m_intent = new Intent(this, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 2, m_intent, 0);
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timePeriod, pi);

Put logout code in YourService.

Shaishav
  • 5,282
  • 2
  • 22
  • 41
0

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 :)

Lubomir Babev
  • 1,892
  • 1
  • 12
  • 14