使用Android

时间:2019-07-18 09:58:23

标签: android sharedpreferences

嗨,在下面的代码中,我正在尝试使用共享的首选项进行一次登录。

为此,我们有三个活动Splashscreen-> Login-> Navigation 假设凭据正确无误,然后我们将重定向到登录屏幕,然后如果下次取消打开应用程序,它将显示导航屏幕。

但是下次它会在启动画面中显示

启动画面:

public class SplashActivity extends AppCompatActivity {
    private int TIME_OUT=3000;/*3 seconds*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        getSupportActionBar ().hide ();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent=new Intent(SplashActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();

                Shared shared=new Shared (getApplicationContext ());
                //to change the boolean value as true
                shared.secondtime ();
            }
        },TIME_OUT);

    }
}

Shared.java:

public class Shared {

    //to create sharedprefences file
    SharedPreferences sharedPreferences;
    //to edit the sharedprefences file
    SharedPreferences.Editor editor;
    //context pass the references to another class
    Context context;
    //mode should be private for sharedpreferences file
    int mode=0;
    //sharedpreferences file name
    String Filename="sdfile";
    //store the boolean value with respect to key id
    String Data="b";

    //create constructor to pass memory at runtime to the sharedfile


    public Shared(Context context) {
        this.context = context;
        sharedPreferences=context.getSharedPreferences (Filename,mode);
        editor=sharedPreferences.edit ();
    }

    //for second time user
    public void secondtime(){
        editor.putBoolean (Data,true);
        editor.commit ();
    }

    //for first time user
    public void firsttime(){

        if(!this.login()){

            Intent intent=new Intent (context,LoginActivity.class);
            intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity (intent);

        }
    }
    //to get the default values as false
    private boolean login(){

        return sharedPreferences.getBoolean (Data,false);

    }
}

0 个答案:

没有答案