开发者

Call something once in app lifecycle?

In order to call some method just once in the a开发者_运维问答pp's lifecycle, not each time the app is launched, where should I place such method?

In onCreate() or somewhere else?


It should be in Application.onCreate() guarded by some SharedPreference boolean variable.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("firstRun", true)) {            
    once(); // <-- your function
    prefs.edit().putBoolean("firstRun", false).commit();
}


You can add it to onCreate() and only call the method if it hasn't been initialized/called previously.

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

If you are looking to call this method only once ever, I would take a look at most answers in here recommending using Preferences. But if you are talking about once per time the app is brought to life, this should be achieved in onCreate(), as this should only be called once the app is initialized and started.


Create a variable in shared preferences that counts app open times then if 0 you call the method Happy coding :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜