When User click Home button app is going to background,if user open the app from background then it should go to login screen instead of last activity...please help me.
-
Override Activity onResume and put the Login there. – from56 Jun 25 '17 at 17:24
3 Answers
If you have multiple Activities it will be probably a pain to track "all activities are paused - go to login" or something similar. What you can do, which will probably be a lot easier:
- You have one Login Activity
- Have a Main Activity with different fragments
Assuming you want some kind of "login timeout" you can track the onStop/onResume of the Main Activity like this:
@Override
protected void onPause() {
activityWasPausedOn = DateTime.now().getMillis();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
Seconds seconds = Seconds.secondsBetween(new Instant(activityWasPausedOn), new Instant());
if (seconds.getSeconds() >= 200) { //login timeout?
//go to login activity
Intent i = new Intent(....);
startActivity(...);
finish();
}
}
- 2,375
- 1
- 25
- 41
-
-
1Oh sorry, this comes from JodaTime. Of course you can do something similar without JodaTime. See: https://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – chrjs Jun 25 '17 at 18:43
There is no exact callback function for android home key press. You should put logout handling code in the onPause() or onResume() methods depending upon the no of activities.
If you have only two activities, try this:
@Override
protected void onPause() {
super.onPause();
if (!isFinishing()) {
finish();
//logout();
}
}
- 15,949
- 6
- 45
- 59
-
I have total five activities....by overiding onresume or onpause methods im facing a problem ,If im going from first activity to second activity then if im pressing back button its was going to login screen :( – Praveen Reddy Jun 25 '17 at 17:40
-
You're going to have to track whether the user is logged in or needs to log in. – Eugen Pechanec Jun 25 '17 at 18:40
You can override the onPause and onResume methods to achieve this.
As you mentioned that you had an issue with the back button leading back to the login screen, you can fix this by using
finishAffinity();
It is used to finish the current activity as well as all activities immediately below it. It is commonly used for logout scenarios.
You can implement the logout logic on onPause() and call finishAffinity there (Removes all activities from stack, so that hitting the back button wouldn't give you trouble), and then take the user to the login page on onResume().
- 1,940
- 24
- 23
-
`you can fix this by using finishAffinity();` When do you call it? What does it do? Please be descriptive about your code. – Eugen Pechanec Jun 25 '17 at 19:20
-