1

I have the MainActivity which is welcome activity and some other ones.
Lets suppose Act1, Act2 and Act3.
I want the program automatically redirect from MainActivity directly to last visited activity on every app launch.
whether Act1, Act2 or Act3
Well, I tried to do this jump from main activity to last visited activity, but it didn't work.
here's code what I've already tried and didn't work:

MainActivity:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadLocale();
        setContentView(R.layout.activity_main);

        SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        int restoredLevel = prefs.getInt("level", 0);
        if (restoredLevel > 0) {
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
        }
    }

Act1:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.Act1);

        SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
        editor.putInt("level", 1);
        editor.apply();
    }

(I simply want to change launcher activity depending on last visited activity, if you know any better solution for my problem, I will be thankful)

Hexley21
  • 566
  • 7
  • 16
  • Why do you want to do that? If the app hasn't been killed by the user, the system will automatically try to reload the last state the app was in when the app is restore from recent apps by the user. So you should not have to handle it manually. – Eselfar Dec 21 '20 at 02:34
  • I mean if app is killed, so last visited activity will everytime reload when app is opened – Hexley21 Dec 21 '20 at 02:37
  • 1
    Your approach is correct then. However I suggest you to read this about shared preferences: https://developer.android.com/training/data-storage/shared-preferences What you are doing at the moment is you store the value into the shared preference of activity Act1 and try to retrieve it from the shared preferences of MainActivity. So MainActivity can't find the value. Use `getDefaultSharedPreferences()` or one you name yourself – Eselfar Dec 21 '20 at 02:49
  • Yeah, I fixed it and it works now but at the start, i can see MainActivity a little and how to fix that? – Hexley21 Dec 21 '20 at 03:32
  • 1
    You should use an Activity with no UI to select the one you want to display to the user. In order to do that you need to **not** call `setContentView ` and call `finish()` after calling `startActivity()` – Eselfar Dec 21 '20 at 03:34
  • Well, now MainActivity doesn't show Thank you very much, you gave me a great idea – Hexley21 Dec 21 '20 at 03:57

0 Answers0