我有一个仅在第一次打开应用程序时运行的Activity。每次我再次打开应用程序时,此活动都不会运行(这没关系)。当我第一次打开我的应用程序时按下后退按钮时出现问题。该活动再次出现,我不希望这种情况发生。我怎样才能防止这种情况发生?
这是我的主要活动的onCreate上的SharedPreferences代码(该变量在外部创建):
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
这是onResume方法,让我的应用知道它是否第一次运行:
`@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();
}
}`
答案 0 :(得分:1)
在finish()
上致电MainActivity
,然后启动Intent
以指向下一个Activity
。您也可以在AndroidManifest.xml
中声明noHistory=true,以防止Activity
出现问题。
您还可以使用PackageManager.setComponentEnabledSetting(...)完全更改您的发射器"活动一旦被查看。
答案 1 :(得分:0)
因为您的活动在starActivity之后完成。请使用此方法,检查工作代码:
@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);
}
}