Accessing Resources without a Context
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"
... >
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.
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);