Whenever I click on my app icon, it always opens on the login screen, even if I’ve already opened it on another page before and even if I just go back to the app’s home screen, clicking the app returns to the page login . I wonder if I can guarantee that it will always open on the last screen I stopped at, unless I have completely exited the application.
Asked
Active
Viewed 495 times
-1
-
Use [`SharedPreferences`](https://developer.android.com/training/data-storage/shared-preferences). – ADM Jul 15 '20 at 04:23
-
This is standard Android behaviour if you have not used any special `launchMode`s in your manifest. If you are experiencing this problem you are probably seeing this nasty Android bug: https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508#16447508 To verify, install your app on the phone, then force close the app (Settings->Apps->Your App->force close) and then start your app by clicking the icon from the HOME screen, go to another `Activity`, press HOME, launch the app again from HOME screen and it should work. – David Wasser Jul 15 '20 at 21:22
-
The answer to use `SharedPreferences` for this is only necessary if you want to return to where you left off after days or weeks of non-use. Generally speaking this is not necessary or desirable behaviour. – David Wasser Jul 15 '20 at 21:23
1 Answers
2
For this you can use Shared Preferences. Each time user stops the app you should store the name of the activity in the memory, So next time you open the app, you can read the file and check which activity was previously used. Write to the file:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
And for every activity override this method:
@override
public void onDestroy() {
Editor editor = sharedpreferences.edit();
editor.putString("LastOpened", "activity_name");
editor.apply();
}
To open the app in previously destroyed activity, write this in login activity:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("LastOpened", "");
switch(name) {
case "LoginActivity": {
//do nothing
}
case "OtherActivity" : {
startActivity(new Intent(this, OtherActivity.class));
....
}

Bensal
- 3,316
- 1
- 23
- 35