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?
Asked
Active
Viewed 1,235 times
-2

Radouane ROUFID
- 10,595
- 9
- 42
- 80

Malik
- 3
- 3
-
what you have tried? – Dipnesh Parakhiya Jul 28 '16 at 06:55
-
I have developed a a library to take care of this type of use case please feel free to take a look https://github.com/jose96043/TimezOut – joseporto Dec 31 '16 at 03:27
2 Answers
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