Getting the Application Context

后端 未结 6 1208
梦如初夏
梦如初夏 2020-12-02 23:16

This might be a simple question but I just wanted to make sure I am right.

In my android application I have a constructor that uses:

activity.getApp         


        
6条回答
  •  猫巷女王i
    2020-12-03 00:10

    I have adapted yuku's answer with a non static direct context reference.

    Create a class domain.company.pseudo.ApplicationName which extends android.app.Application.

    package hypersoft.systems.android;
    
    import android.app.Application;
    
    public class Starbox extends Application {
    
      public static Starbox instance;
    
      @Override
      public void onCreate() {
        super.onCreate();
        instance = this;
      }
    
    }
    

    In this sample, my full application package name is hypersoft.systems.android.starbox.

    Now, modify your AndroidManifest.xml tag to have the attribute android:name="hypersoft.systems.android.Starbox", and be sure the Starbox.java class file is located in the project component directory: android rather than starbox.

    With all this done, you can now import hypersoft.systems.android.Starbox, and in your code you can get the ApplicationContext by calling Starbox.instance.getApplicationContext()

    Successfully compiling with build tools 26 and api 26 (Android 8.0) with min sdk version 14 (4.0).

提交回复
热议问题