简体   繁体   English

启动具有特定活动的Android应用

[英]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'. 当应用启动或恢复时,我想基于“ SharedPrefences”中设置的变量将用户重定向到特定的“ Activity”。

To do this I was considering having a method that checks for SharedPreferences status variable and redirects to the correct activity: 为此,我正在考虑使用一种方法来检查SharedPreferences状态变量并重定向到正确的活动:

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: 然后,我可以为应用程序中的每个活动在每个“ onResume”方法中调用此方法:

    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. 这将意味着用户从技术上讲不能返回上一个活动,因为当他们调用它时,它会调用onResume,它将被重定向到与当前用户相对应的状态。

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. 我相信这是正常的方法,除非您还可以添加finish()方法的调用,如果您需要在这种情况下关闭MainActivity的话。

Besides, don't forget break statements: 此外,不要忘记break语句:

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. 这将节省您不必要的活动启动检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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