Android的getResources()非Activity类 [英] android getResources() from non-Activity class
问题描述
我试图加载我从顶点数组资产/ model.txt
我有OpenGLActivity,GLRenderer和为MyModel类
我加入这行来OpenGLActivity:
I'm trying to load my vertices array from assets/model.txt I have OpenGLActivity, GLRenderer and Mymodel classes i added this line to the OpenGLActivity:
public static Context context;
和这为MyModel类:
And this to Mymodel class:
Context context = OpenGLActivity.context;
AssetManager am = context.getResources().getAssets();
InputStream is = null;
try {
is = am.open("model.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner s = new Scanner(is);
long numfloats = s.nextLong();
float[] vertices = new float[(int) numfloats];
for (int ctr = 0; ctr < vertices.length; ctr++) {
vertices[ctr] = s.nextFloat();
}
但does'n工作(
But it does'n work (
推荐答案
我发现在Android中它不要在静态变量对它们的引用与活动(以及大多数其他类)非常重要。我会尽量避免他们不惜一切代价,他们热爱导致内存泄漏。但有一个例外,该应用程序对象的引用,这当然是一个上下文
的。保持在一个静态的引用,这决不会泄漏内存。
I have found in Android it is very important with Activities (and most other classes) not to have references to them in static variables. I try to avoid them at all costs, they love causing memory leaks. But there is one exception, a reference to the application object, which is of course a Context
. Holding a reference in a static to this will never leak memory.
所以我做什么,如果我真的需要有对资源的全球背景是扩展应用程序对象,并添加静态get函数的上下文。
So what I do if I really need to have a global context for resources is to extend the Application object and add a static get function for the context.
In the manifest do....
<application android:name="MyApplicationClass" ...your other bits....>
和Java中....
And in Java....
public class MyApplicationClass extends Application
{
private Context appContext;
@Override
public void onCreate()
{//Always called before anything else in the app
//so in the rest of your code safe to call MyApplicationClass.getContext();
super.onCreate();
appContext = this;
}
public static Context getContext()
{
return appContext;
}
}
这篇关于Android的getResources()非Activity类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!