在我的 Android 应用程序中,如何在应用程序启动时运行特定功能?如果可能的话,我不想将它与特定 Activity 联系起来。将它绑定(bind)到特定 Activity 的 onCreate 方法是行不通的,因为即使屏幕方向发生变化,onCreate 也会被调用。
最佳答案
对于每次启动应用程序时只运行一次的函数,您有几个选择。
-您可以使用要运行的函数创建单例,并使函数调用以单例中的静态 bool 标志为条件。由于静态单例在任何给定 Activity 的外部,因此当您旋转屏幕并创建/销毁单个 Activity 时,该标志不会恢复。虽然此解决方案优于 Application 子类化,但您确实需要确保函数调用“mySingleton.runOnce(params...)”在构成 Activity 入口点的每个 Activity 中(因此您可以从 Intent 进入的任何地方)一个外部应用程序)
-您可以子类化 Application类并重写它的 onCreate 方法。这不是首选解决方案:从文档中,
There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
希望这对您有所帮助!
关于应用程序启动时的 Android 事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302249/