Accessing Resources without a Context

别等时光非礼了梦想. 提交于 2019-11-27 14:18:39

Use

Resources.getSystem().getString(android.R.string.someuniversalstuff)

You can use it ABSOLUTELY EVERYWHERE in your application, even in static constants declaration! But for system resources only.

For local resources use that solution.

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:

<application
 android:name=".MyApplication"
 ... >

Unfortunately I don't think there is a real way around this. I lay mine out something like this, and also pass in the getApplicationContext() instead of the activity context.

public static AppController getAppController(Context context){
    if(self == null) {
        //Create instance
        self = new AppController();
    }

    return self;
}

And then:

appController = AppController.getAppController(getApplicationContext());

I would recommend doing the following: Rather than passing context everywhere make your activity class a singleton class with a public function that returns the context:

private static ActivityMain instance;

Initialize inside onCreate() before super.onCreate():

instance = this;

Then add these public functions to your activity:

/** Get singleton instance of activity **/
public static ActivityMain getInstance() {
    return instance;
}

/** Returns context of this activity **/
public static Context getContext(){
    return instance.getApplicationContext();
}

Now you can use the following anywhere in any class:

Context context = AntiMorphActivity.getContext();
String packageName = context.getPackageName();
int id = context.getResources().getIdentifier("web_page", "raw", packageName);
andrew pate

The stackoverflow answer to the question below shows how to use POJO to obtain a stream to a resource, if you supply its path. This might be useful in cases you need to select a specific resource from one of many.

Is it possible to read a raw text file without Context reference in an Android library project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!