简体   繁体   English

如何初始化Application类并在android中存储getApplicationContext()?

[英]How to initialize an Application class and store getApplicationContext() in android?

I have declared an Application class inside my app: 我在我的应用程序中声明了一个Application类:

public class application extends Application {

    String TAG="joshtag";//app.TAG;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Initializing APP");
        initializeSingletons(getApplicationContext());
    }

    protected void initializeSingletons(Context c){
        Log.e(TAG, "...preparing to Initialize Singleton");
        app.initInstance(c);
    }
}

As you may imagine, I want this class to run as soon as my App launches, with the objective of initializing a Singleton class (this singleton class does not extend any other class and will contain a variable to store getAppContext). 正如您可能想象的那样,我想在我的App启动时运行此类,目的是初始化Singleton类(此单例类不会扩展任何其他类,并且将包含存储getAppContext的变量)。 However, the Log messages never trigger inside "onCreate" and "initializeSingleton", and the Singleton is not initialized. 但是,Log消息永远不会在“onCreate”和“initializeSingleton”内触发,并且Singleton未初始化。 My ultimate goal is to store a global getAppContext variable that I can use inside classes who does not inherit it. 我的最终目标是存储一个全局的getAppContext变量,我可以在不继承它的类中使用它。 If I am approaching the issue with the wrong mindset, let me know and mention why. 如果我以错误的心态接近问题,请告诉我并提及原因。

不要忘记在AndroidManifest.xml添加对应用程序类的引用。

<application ... android:name="com.yourPackageName.application ">

Was facing the same problem. 面临同样的问题。 To initialise an Application class we need to specify it in manifest file with corresponding package name inside application tag. 要初始化Application类,我们需要在manifest文件中指定它,并在application标记内包含相应的包名。

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

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