我想使用SharedPreference只启动一次启动活动,它是如何发生的。任何帮助将受到高度赞赏。谢谢
Thread thread;
MediaPlayer audio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
if (first_run == true){
thread = new Thread(){
@Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
audio.release();
}
}
};
thread.start();
}
}
答案 0 :(得分:0)
试试这个:
声明
public static final String MyPREFERENCES = "MyPrefs";
public static final String ID = "idKey";
SharedPreferences sharedPreferences;
现在你的onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
String first = (sharedPreferences.getString("First", ""));
if (!first.equals("true")) {
thread = new Thread(){
@Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("First", "true");
editor.commit();
finish();
audio.release();
}
}
};
thread.start();
}
}
答案 1 :(得分:0)
而不是sharedprefrence
,我建议您使用静态布尔值,如 - isFirstTime
并默认设置为true
,并在第二个活动(在splash旁边)设置它到false
。每当你杀死应用程序静态值将变为死亡。检查Splash的onCreate
-
if(!isFirstTime){
goToNextActivity();
}else{
//continue splash code
}
如果你想使用共享首选项,那么使用相同的逻辑,取一个布尔值并将其保存在共享首选项中 -
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
并在下一个活动中将其设置为false
或清除值。通过调用editor.clear();
并在共享pref具有某些值或isFirstTime
时检查启动,并相应地执行下一个代码。