我有需要获得它的一个引用类的应用程序的 AssetManager
。此类不扩展任何种类的Android UI类,因此它不具有的getContext()
的方法,或者类似的话。是否有某种静态 Context.getCurrentApplicationContext()
类型的方法?
要澄清:我的类拟用于像库,对于其他的应用程序。它没有相关的的AndroidManifest.xml
或在其上调用它的上下文控制。
公共类应用扩展应用{
将安卓:名称
属性的<应用>
标记中的 AndroidManifest.xml中
来指向新的类,如: 安卓名=应用程序
在您的应用程序实例的的onCreate()
方法,保存环境(例如:这
)的静态场名为应用
并创建一个返回该领域的静态方法,例如: getApp()
:
这是它应该如何看:
公共类应用扩展应用{
私有静态语境mContext;
@覆盖
公共无效的onCreate(){
super.onCreate();
mContext =这一点;
}
公共静态上下文的getContext(){
返回mContext;
}
}
现在,您可以使用: App.getContext()
时,你希望得到一个上下文,然后 getAssetManager()
(或 App.getContext()。getAssetManager()
)。
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.
Application
, for instance public class App extends Application {
Set the android:name
attribute of your <application>
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()
).