我有一个活动,我只想在第一次运行应用程序时运行。我检查了一个返回布尔值的指定共享首选项。如果它返回true,它将被启动并且它将被设置为false,以便下次打开应用程序时它不会运行。但我的实施出错了。每次打开BeforMain1活动都会被打开。有人可以告诉我我的代码中有什么问题吗?
sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
boolean firstTime=sharedPreferences.getBoolean("first", true);
if(firstTime) {
editor.putBoolean("first",false);
Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
}
答案 0 :(得分:5)
您忘记提交SharedPreferences更改,
if(firstTime) {
editor.putBoolean("first",false);
//For commit the changes, Use either editor.commit(); or editor.apply();.
editor.commit(); or editor.apply();
Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
startActivity(intent);
}else {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
}
答案 1 :(得分:0)
我认为这会对你有所帮助,对不起我的英语。
SharedPreferences validation;
SharedPreferences.Editor editorValidation;
validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);
if(validation.contains("firsttime"))
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class); //create intent with second screen
startActivity(intent); //call second screen
/*
//this code you will put in your application but is redundant... with the else and comprobation if the firsttime is true or false
if(Validation.getBoolean("firsttime", false))
{
Intent intent = new Intent(SplashScreen.this, MainActivity.class); //create intent with second screen
startActivity(intent); //call second screen
}else{
//if the sharedpreference firsttime is true then call the first screen but it is redundant
Intent intent = new Intent(getApplicationContext(), BeforeMain1.class); //create var intent with the screem for first time
startActivity(intent); //call new screen
}
*/
}else{
//put the sharedpreference boolean firsttime equal to false
editorValidation= validation.edit(); // edit the sharedpreference
editorValidation.putBoolean("firsttime",false); // put false to firsttime
editorValidation.apply(); //apply(); runs in background, no return anything and commit(); return true or false
//call screen before the main - for the first time
Intent intent = new Intent(getApplicationContext(), BeforeMain1.class); //create var intent with the screem for first time
startActivity(intent); //call new screen
}