共享的首选项未按预期工作

时间:2019-06-20 09:04:35

标签: android

下面是我到我项目的MainActivity.java中的代码,这是我的应用程序的欢迎界面,仅当用户打开应用程序时才会出现。否则,用户应该可以看到Medicine_Activity.java,当用户按下MainActivity上的“入门”按钮时也会触发该信息。为了实现这一点,我遇到了一种称为SharedPreferences的东西,并试图实现它。但是它没有按预期工作,在启动Medicine_Activity之前,MainActivity会闪烁一秒钟。我是新来的,请帮帮我

以下是一个视频片段,用于查看此错误的实际操作-https://www.dropbox.com/s/fqbo9urb6xnh3pd/WhatsApp%20Video%202019-06-20%20at%202.12.50%20PM.mp4?dl=0

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnGetStarted;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
        if(!previouslyStarted) {
            SharedPreferences.Editor edit = prefs.edit();
            edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
            edit.apply();
        } else{
            Intent intent = new Intent(this, Medicine_Activity.class);
            startActivity(intent);
        }
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
        getSupportActionBar().hide(); // hide the title bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
        setContentView(R.layout.activity_main);

        Button btnGetStarted = findViewById(R.id.btnGetStarted);
        btnGetStarted.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, Medicine_Activity.class);
        startActivity(intent);
    }
}

1 个答案:

答案 0 :(得分:0)

在存储{{1}的commit()true的同时使用finish()

MainActivity

简短说明:if(!previouslyStarted) { SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(getString(R.string.pref_previously_started), true); edit.commit(); } else{ Intent intent = new Intent(this, Medicine_Activity.class); startActivity(intent); finish(); } 同步写入数据(阻塞从其调用的线程)。然后它会通知您有关操作成功的信息。但是,commit()计划将数据异步写入。它不会通知您有关操作成功的信息。

引用Documentation

  

与commit()会将其首选项同步写到持久性存储中的方法不同,apply()立即将其更改提交到内存中的SharedPreferences,但会启动对磁盘的异步提交,并且不会收到任何失败的通知

相关问题