检测首次运行 [英] Detect First Run
问题描述
我想检测是否我的应用程序已经运行之前,通过使用该code:
I am trying to detect if my app has been run before, by using this code:
(这是我的默认的Android活动)
(This is in my default Android activity)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
当我第一次运行该应用程序,它说第一次,当我运行它第二次,第一次和第三次,第一次......
When I first run the app it says first time, when I run it a second time, first time, and a third, first time....
我使用的是实际的Android设备,我不使用运行按钮各一次。我与Eclipse运行按钮运行应用程序一次,然后我关闭它的图标的应用程序和preSS在我的手机上。
I am using an actual Android device and I am not using the run button each time. I run the app once with the Eclipse run button, then I close the app and press on its icon on my phone.
是不是有什么毛病我code?
Is there something wrong with my code?
谢谢!
推荐答案
savedInstanceState
则多为状态之间的切换,如暂停/恢复,那种事。它必须由您来创建,也。
savedInstanceState
is more for switching between states, like pausing/resuming, that kind of thing. It must always be created by you, also.
你想在这种情况下,什么是<一个href="http://developer.android.com/reference/android/content/Shared$p$pferences.html"><$c$c>Shared$p$pferences$c$c>.
What you want in this case is SharedPreferences
.
事情是这样的:
public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if (firstRun) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.commit(); // Save all changed settings
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
我基本上把这个code直接从用于存储文档选项并将其应用到你的情况。这是一个很好的概念,早期的学习。
I basically took this code directly from the documentation for Storage Options and applied it to your situation. It's a good concept to learn early.
这篇关于检测首次运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!