检测首次运行

foo*_*512 1 java android oncreate

我试图通过使用此代码检测我的应用程序之前是否已运行:

(这是我默认的Android活动)

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


 }
Run Code Online (Sandbox Code Playgroud)

当我第一次运行应用程序时它第一次说,当我第二次运行它时,第一次运行它,第三次运行它,第一次运行它....

我使用的是实际的Android设备,而且每次都没有使用运行按钮.我使用Eclipse运行按钮运行应用程序一次,然后关闭应用程序并按下手机上的图标.

我的代码有问题吗?

Eri*_*ric 10

savedInstanceState更像是在状态之间切换,比如暂停/恢复,这种事情.它也必须始终由您创建.

在这种情况下你想要的是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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我基本上直接从存储选项的文档中获取此代码,并将其应用于您的情况.这是一个很早就学会的好概念.