在应用程序生命周期中调用一次?

发布于 2024-12-02 06:40:58 字数 103 浏览 5 评论 0原文

为了在应用程序的生命周期中仅调用某些方法一次,而不是每次 应用程序启动后,我应该在哪里放置这样的方法?

在 onCreate() 或其他地方?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坦然微笑 2024-12-09 06:40:58

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

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

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();
}
与风相奔跑 2024-12-09 06:40:58

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

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

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

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.

北城孤痞 2024-12-09 06:40:58

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文