Is it possible to configure an android app so that if a user has opened your app, launched numerous activities, then returns to the home screen and relaunches your app again, instead of going to the main activity they will instead be taken to the activity highest on the stack (the most recent activity in your app)?
It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.
Declare A in your manifest with the android:launchMode="singleTask" . This way, when you call startActivity() from your other activies, and A is already running, it will just bring it to the front.
Activities will very often need to support the CATEGORY_DEFAULT so that they can be found by Context. startActivity(). So, CATEGORY_DEFAULT can appear number of times. Android does not grab whichever one appears first in the manifest but it starts with activity having CATEGORY_LAUNCHER.
When launched via icon on the home screen, Android will always start the activity with the android.intent.action.MAIN
filter in your AndroidManifest.xml
, unless the application is already running (in which case it will obviously restore the activity on top of the stack).
To achieve what you described you can simply store the last visible activity in SharedPreferences
and have a Dispatcher activity that starts the last activity according to the preferences.
So in every activity you want to re-start automatically:
@Override protected void onPause() { super.onPause(); SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE); Editor editor = prefs.edit(); editor.putString("lastActivity", getClass().getName()); editor.commit(); }
And a Dispatcher activity similar to the following:
public class Dispatcher extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Class<?> activityClass; try { SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE); activityClass = Class.forName( prefs.getString("lastActivity", Activity1.class.getName())); } catch(ClassNotFoundException ex) { activityClass = Activity1.class; } startActivity(new Intent(this, activityClass)); } }
Remarks
onPause
overrideandroid.intent.action.MAIN
actionIt's not that complex. You just need to manipulate the manifest.
AndroidManifest.xm
<activity android:name=".MainActivity" android:alwaysRetainTaskState="true" android:exported="true" . . .
Read about the 'android:exported' & 'android:alwaysRetainTaskState' here:
android:exported
android:alwaysRetainTaskState
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With