【问题标题】:Android - two main activitiesAndroid - 两个主要活动
【发布时间】:2020-08-10 08:22:14
【问题描述】:

我构建了一个应用程序,用户在进入我的应用程序之前需要登录。 当他们再次打开应用程序时,我希望他们将获得主要活动(而不是登录活动)。 现在,每个进入的用户首先会看到登录一秒钟,然后移动到主要活动。 有没有办法让用户先进入主Activity?

【问题讨论】:

  • 您需要一个标志来告诉用户他是否已经注册。为此,您可以使用 SharedPreferences 来设置您的标志。这是一个简单的例子:this way

标签: java android android-studio android-activity


【解决方案1】:

在这种情况下,请使用 SharedPreferences

第 1 步:

添加闪屏活动,作为用户的欢迎屏幕。

第 2 步:

在你的启动画面中:

private SharedPreferences pref;
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
pref = getSharedPreferences("your package name", MODE_PRIVATE);
if (pref.getBoolean("firstrun", true)) {
 

 //edit your shared preference in order not be true all the time
 pref.edit().putBoolean("firstrun", false).apply();
 //check if this is the first run 
 // start Sign in activity
 }
 else{
 //if not the first run, navigate to your mainactivity not sign in activity.
 }
}

【讨论】:

    【解决方案2】:

    假设你有MainActivityLoginActivity

    LoginActivity

    onCreate()中检查用户是否登录

    SharedPreferences prefs = getSharedPreferences("LogIn", MODE_PRIVATE); 
    String state = prefs.getString("state", "default");
    
    if(state.equals("logged_in")){
    
    //take directly to MainActivity because the user is logged in
    startActivity(new Intent(LoginActivity.this,MainActivity.class));
    
    }else{
    
    //do nothing the user didn't log in yet
    
    }
    

    当您在用户点击按钮后登录时:

    //set a flag in shared prefrences that the user logged in before going to MainActivity
    
    SharedPreferences.Editor editor = getSharedPreferences("LogIn", MODE_PRIVATE).edit();
    editor.putString("state", "logged_in");
    editor.apply();
    
    //take the user to the MainActivity
    
    startActivity(new Intent(LoginActivity.this,MainActivity.class));
    
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多