简体   繁体   English

Android 每次启动应用程序时运行一段代码,但在应用程序最小化和重新打开时不运行

[英]Android run a piece of code each time the app is started but not when the app is minimised and reopened

Need to run a piece of code when the app each time the app is started and not while it is running or and not when main activity is navigated away from and returned to每次启动应用程序时都需要运行一段代码,而不是在运行时运行,或者在主活动被导航离开并返回时不需要

just need to run the code once on when the app starts up只需要在应用程序启动时运行一次代码

Without knowing more about your actual use case, the only thing that I can suggest is -在不了解您的实际用例的情况下,我唯一可以建议的是 -

  • Override attachBaseContext() in your Application class (Create one if you don't have it)在您的应用程序 class 中覆盖 attachBaseContext()(如果没有,请创建一个)

  • Call super.attachBaseContext()调用 super.attachBaseContext()

  • Write the code you need to run in the method body.在方法体中编写需要运行的代码。 (As always, for any long-standing or db/network operations, don't do it on the main thread) (与往常一样,对于任何长期存在的或数据库/网络操作,不要在主线程上执行)

attachBaseContext() is one of the first things to be called when your app is launched so I think this should work for you. attachBaseContext() 是您的应用程序启动时首先要调用的东西之一,所以我认为这应该适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM