What's the best way to skip an Activity [dupli

2019-09-17 19:36发布

问题:

This question already has an answer here:

  • Having trouble skipping an activity 2 answers

I'm developing an app in which a user logs in to his dashboard and stays logged in until he logs out (I mean if the app is closed and restarted, he still stays logged in). I'm using SharedPreferences to check if the user is actually logged in.

Preference.java

public class Preference {

    Context context;
    SharedPreferences sharedPref;

    public Preference(Context context){
        this.context = context;
        sharedPref = context.getSharedPreferences("LoginState", 0);
    }

    public boolean getIsLoggedIn(){
        return sharedPref.getBoolean("State", false);
    }

    public void setIsLoggedIn(boolean state){
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("State", state);
        editor.commit();
    }

}

I call the function setIsLoggedIn(true) when the user logs in and setIsLoggedIn(false) when the user logs out. But how to check and skip the LoginActivity if the user is already logged in?

回答1:

Place this condition in your Splash screen

Preference pre = new Preference(SplashScreen.this);
    if(preference.getIsLoggedIn()){
    // move to Login Screen
    }else{
     // move to your mainscreen
    }


回答2:

If LoginActivity is default app activity called by launcher icon you can simply check login on it's onCreate() method and show another activity if user logged in.

onCreate() {
    super.onCreate();
    Preference p = new Preference(this);
    if(p.getIsLoggedIn()) {
       finish();
       // start another app activity here ...
    }

    // ...
}


回答3:

From your first Activity do this

 SharedPreferences.Editor editor = sharedPref.edit();               
    Boolean flag = sharedPref.getBoolean("state", false);
                    if(flag==false){
    // Start your login ACTIVITY
                    }else{
                        //Start your activity which you want to hit after login
                    }


回答4:

I think you should add some code to your LoginActivity's onResume or onCreate method, that checks, if the user is logged in, and if so fire an intent that starts the Dashboard Activity. Something like this.

public void onResume() {
    super.onResume();
    if (Preferences.getIsLoggedIn()) {
        startActivity(new Intent(this, DashboardActivity.class));
    }
}