What's the best way to skip an Activity [duplicate]

梦想与她 提交于 2019-12-13 06:21:04

问题


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));
    }
}


来源:https://stackoverflow.com/questions/21827797/whats-the-best-way-to-skip-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!