Accessing Resources without a Context

后端 未结 5 1726
小鲜肉
小鲜肉 2020-12-03 04:31

I\'m trying to put configuration, such as URLs/etc, into a resource folder for a utility class to use. However, I don\'t want to pass the Context from the activities everywh

5条回答
  •  星月不相逢
    2020-12-03 05:13

    You could extend the main application class and provide universal helpers there to access resources. This relieves the need for context as the application would provide the context instead of the caller. The application class is singleton style and should always be available while any portion of your application is running (including services).

    public class MyApplication extends Application {
     protected static MyApplication instance;
    
     @Override
     public void onCreate() {
      super.onCreate();
      instance = this;
     }
    
     public static Resources getResources() {
      return instance.getResources();
     }
    }
    

    This provides you access to:

    MyApplication.getResources()....
    

    Be sure to declare your custom application in your manifest to gain access to this. Assuming your custom application is in the root of your application's namespace:

    
    

提交回复
热议问题