Is it possible to get application's context in an Android Library Project?

后端 未结 5 1442
有刺的猬
有刺的猬 2020-12-04 18:53

I would like to get the context of application which has reference/hosted my library at run-time inside one class of my library project. Is it possible? If yes, how?

5条回答
  •  醉话见心
    2020-12-04 19:38

    There is one more way, add application class in your library project:

    /**
     * Base class for those who need to maintain global application state.
     */
    public class LibApp extends Application {
    
      /** Instance of the current application. */
      private static LibApp instance;
    
      /**
       * Constructor.
       */
      public LibApp() {
        instance = this;
      }
    
      /**
       * Gets the application context.
       * 
       * @return the application context
       */
      public static Context getContext() {
        return instance;
      }
    
    }
    

    Then in your regular project make the real application class extend LibApp:

    /**
     * Base class for those who need to maintain global application state.
     */
    public class App extends LibApp {
    
      @Override
      public void onCreate() {
        super.onCreate();
      }
    
    }
    

    Make sure that you have "Name" defined in AndroidManifest:

    
    

    and that your App class is in the base package.

    You can then use LibApp.getContext() your library project to get the application context of the application that is using the library.

    This may not be good solution but it works for me. I am sharing it because it might be useful to somebody else.

提交回复
热议问题