1

In order to call some method just once in the app's lifecycle, not each time the app is launched, where should I place such method?

In onCreate() or somewhere else?

4

3 回答 3

6

它应该Application.onCreate()由一些SharedPreference布尔变量保护。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("firstRun", true)) {            
    once(); // <-- your function
    prefs.edit().putBoolean("firstRun", false).commit();
}
于 2011-09-01T15:29:39.750 回答
2

您可以将其添加到该方法,onCreate()并且仅在之前未初始化/调用该方法时才调用该方法。

protected void onCreate(Bundle b) {
    if(shouldCall()) { // I know if the method has been called before
        callMethodJustOnce();
    }
}

如果您只想调用此方法一次,我会在此处推荐 using 中查看大多数答案Preferences。但是,如果您在每次应用程序启动时谈论一次,这应该在 中实现onCreate(),因为这应该只在应用程序初始化和启动后调用。

于 2011-09-01T15:30:32.127 回答
0

在共享首选项中创建一个变量,计算应用程序打开时间,然后如果为 0,则调用方法快乐编码:D

于 2011-09-01T15:31:09.437 回答