我的第一项活动:
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.buttonid);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,Main2Activity.class));
}
});
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
} else {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
}
我的第二项活动:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
答案 0 :(得分:1)
更改您的代码。首先保存然后打开活动。
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
答案 1 :(得分:0)
我就是这样做的,希望有所帮助:
onCreate
if (pref.getString("someConstant",null) == null){
//This is my first time, no value in sharedpref for "someConstant"
//Feel free to do any logic here if needed
}else{
//not my first time
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
}
现在,在您的第二个活动中,一旦打开,只需在onCreate
SharedPreferences.Editor ed = pref.edit();
ed.putString("someConstant","some random string, does not make difference").commit();
首次启动时,您的应用将没有任何值,因此它将保留在第一个活动中,因为“someConstant”返回null
。进入第二个活动后,共享首选项中的值将被存储,因此在之后的任何新应用启动中,您将直接进入第二个活动