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?
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?
它应该Application.onCreate()
由一些SharedPreference
布尔变量保护。
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("firstRun", true)) {
once(); // <-- your function
prefs.edit().putBoolean("firstRun", false).commit();
}
您可以将其添加到该方法,onCreate()
并且仅在之前未初始化/调用该方法时才调用该方法。
protected void onCreate(Bundle b) {
if(shouldCall()) { // I know if the method has been called before
callMethodJustOnce();
}
}
如果您只想调用此方法一次,我会在此处推荐 using 中查看大多数答案Preferences
。但是,如果您在每次应用程序启动时谈论一次,这应该在 中实现onCreate()
,因为这应该只在应用程序初始化和启动后调用。
在共享首选项中创建一个变量,计算应用程序打开时间,然后如果为 0,则调用方法快乐编码:D