来自非Activity类的android getResources()

use*_*140 3 android opengl-es

我正在尝试从assets/model.txt加载我的顶点数组我有OpenGLActivity,GLRenderer和Mymodel类我将此行添加到OpenGLActivity:

public static Context context;
Run Code Online (Sandbox Code Playgroud)

这到Mymodel类:

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();
    }
Run Code Online (Sandbox Code Playgroud)

但它确实不起作用(

小智 6

我在Android中发现,活动(和大多数其他类)在静态变量中没有引用它们是非常重要的.我试图不惜一切代价避免它们,他们喜欢导致内存泄漏.但是有一个例外,即对应用程序对象的引用,当然是一个Context.在静态中保持引用将永远不会泄漏内存.

因此,如果我真的需要拥有资源的全局上下文,我会做的是扩展Application对象并为上下文添加静态get函数.

In the manifest do....
<application    android:name="MyApplicationClass" ...your other bits....>
Run Code Online (Sandbox Code Playgroud)

而在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;
    }
}
Run Code Online (Sandbox Code Playgroud)