如何使用共享首选项启动一次启动活动



我只想使用共享首选项启动一次启动活动,这是怎么发生的。 任何帮助将不胜感激。谢谢

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

试试这个:

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

而不是sharedprefrence,我想建议您使用静态布尔值,例如 - isFirstTime并将其设置为true默认情况下,并在第二个活动(在飞溅旁边(将其设置为 false .每当你杀死应用程序静态值时,就会失效。入住飞溅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();并在 Splash 中检查共享 pref 是否有一些值或有isFirstTime并相应地执行下一个代码。

最新更新