简体   繁体   中英

Launch Android App with Specific Activity

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM