按返回按钮时,第一个 运行 的 SharedPreferences 未保存
SharedPreferences on first run are not saved when pressing Back Button
我有一个 Activity,在第一次打开应用程序时只有 运行 秒。每次我再次打开应用程序时,这个 Activity 不会 运行(这没关系)。当我第一次打开我的应用程序时按下后退按钮时出现问题。 Activity 再次出现,我不希望这种情况发生。我怎样才能防止这种情况发生?
这是我在主 activity 的 onCreate 上的 SharedPreferences 代码(变量是在外部创建的):
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
这是 onResume 方法,它让我的应用知道它是否是第一次 运行ning:
`@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
Intent myIntent = new Intent(MainActivity.this, StoryActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.startActivity(myIntent);
prefs.edit().putBoolean("firstrun", false).commit();
}
}`
在启动 Intent
以定向到下一个 Activity
之前,先在您的 MainActivity
上呼叫 finish()
。您还可以在 AndroidManifest.xml
中声明 noHistory=true 以防止 Activity
继续存在。
您还可以使用 PackageManager.setComponentEnabledSetting(...) 来彻底改变您的 "launcher" Activity 一旦它被查看。
因为您的 activity 在 starActivity.Use 之后完成,请检查工作代码:
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
prefs.edit().putBoolean("firstrun", false).commit();
// Do first run stuff here then set 'firstrun' as false
Intent myIntent = new Intent(MainActivity.this, StoryActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(myIntent);
}
}
我有一个 Activity,在第一次打开应用程序时只有 运行 秒。每次我再次打开应用程序时,这个 Activity 不会 运行(这没关系)。当我第一次打开我的应用程序时按下后退按钮时出现问题。 Activity 再次出现,我不希望这种情况发生。我怎样才能防止这种情况发生?
这是我在主 activity 的 onCreate 上的 SharedPreferences 代码(变量是在外部创建的):
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
这是 onResume 方法,它让我的应用知道它是否是第一次 运行ning:
`@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
Intent myIntent = new Intent(MainActivity.this, StoryActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.startActivity(myIntent);
prefs.edit().putBoolean("firstrun", false).commit();
}
}`
在启动 Intent
以定向到下一个 Activity
之前,先在您的 MainActivity
上呼叫 finish()
。您还可以在 AndroidManifest.xml
中声明 noHistory=true 以防止 Activity
继续存在。
您还可以使用 PackageManager.setComponentEnabledSetting(...) 来彻底改变您的 "launcher" Activity 一旦它被查看。
因为您的 activity 在 starActivity.Use 之后完成,请检查工作代码:
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
prefs.edit().putBoolean("firstrun", false).commit();
// Do first run stuff here then set 'firstrun' as false
Intent myIntent = new Intent(MainActivity.this, StoryActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(myIntent);
}
}