How to obtain AssetManager without reference to Context?

2013-11-05 veryyoung 更多博文 » 博客 » GitHub »

原文链接 http://veryyoung.me/blog/2013/11/05/how-to-obtain-assetmanager-without-reference-to-context.html
注:以下为加速网络访问所做的原文缓存,经过重新格式化,可能存在格式方面的问题,或偶有遗漏信息,请以原文为准。


I have a class that needs to obtain a reference to it's application's AssetManager. This class does not extend any sort of android UI class, so it doesn't have a getContext() method, or anything similar. Is there some sort of static Context.getCurrentApplicationContext() type of method?

To clarify: my class is intended to be used like a library, for other applications. It has no associated AndroidManifest.xml or control over the context which is calling it.

The key to this problem is :

Create a subclass of Application, for instance public class App extends Application Set the android:name attribute of your tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App" In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():

This is how it should look:

public class App extends Application{

private static Context mContext;

@Override
public void onCreate() {
    super.onCreate();
    mContext = this;
}

public static Context getContext(){
    return mContext;
}

}

Now you can use: App.getContext() whenever you want to get a context, and then getAssetManager() or App.getContext().getAssetManager().

refer http://stackoverflow.com/questions/4410328/how-to-obtain-assetmanager-without-reference-to-context