【问题标题】:android getResources() from non-Activity class来自非Activity类的android getResources()
【发布时间】:2011-12-11 11:13:17
【问题描述】:

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

public static Context context;

这是 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();
    }

但它不起作用(

【问题讨论】:

    标签: android opengl-es


    【解决方案1】:

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

    所以如果我真的需要资源的全局上下文,我会做的是扩展 Application 对象并为上下文添加一个静态 get 函数。

    In the manifest do....
    <application    android:name="MyApplicationClass" ...your other bits....>
    

    在 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2011-10-16
      • 2013-01-11
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多