When an app launches or resumes, I would like to redirect the user to a specific 'Activity' based on a variable set in 'SharedPrefences'.
To do this I was considering having a method that checks for SharedPreferences status variable and redirects to the correct activity:
private void launchRedirect(Context ctxt) {
Integer status = AppPreferences.getStatus(this);
Intent i = new Intent(MainActivity.this, Activity1.class);
switch (status) {
case 0:
i = new Intent(MainActivity.this, Activity2.class);
case 1:
i = new Intent(MainActivity.this, Activity3.class);
case 2:
i = new Intent(MainActivity.this, Activity4.class);
case 3:
i = new Intent(MainActivity.this, Activity5.class);
}
startActivity(i);
}
And then I could call this method in each 'onResume' method for every activity in my app:
public void onResume(Bundle savedInstanceState) {
launchRedirect(this);
}
This would mean that the user cannot technically go back to the last Activity, because when they call it, it calls onResume, and it will be redirected to the state that corresponds with the current user.
I assume this might lead to some circular bugs though - is there a better way to do this?
Go to "Edit Configurations..." in the "Run" menu. In the left pane, select your application. In the right pane, in the "General" tab, in the "Launch Options" section, there is a "Launch:" dropdown. Select "Specified Activity", and enter the name of your activity as it appears in your Manifest.
To allow other apps to start your activity in this way, you need to add an <intent-filter> element in your manifest file for the corresponding <activity> element.
The intent-filter inside the activity tells Android which Activity to launch.
I believe it is normal way to do it, except you can also add call of finish() method, if you need MainActivity to be closed in this situation.
Besides, don't forget break statements:
private void launchRedirect(Context ctxt) {
Integer status = AppPreferences.getStatus(this);
Intent i = new Intent(MainActivity.this, Activity1.class);
switch (status) {
case 0:
i = new Intent(MainActivity.this, Activity2.class);
break;
case 1:
i = new Intent(MainActivity.this, Activity3.class);
break;
case 2:
i = new Intent(MainActivity.this, Activity4.class);
break;
case 3:
i = new Intent(MainActivity.this, Activity5.class);
break;
}
startActivity(i);
if (/* check if MainActivity should be closed */) {
finish();
}
}
Please make sure you are updating the preference value as per your navigation activtiy. That will save your unnecessary checks for the Activity launching.
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