android – 如何获得具有有效Surface的SurfaceHolder(EGL.eglCreateWindowSurface需要)?

我尝试用EGL初始化GLES(因为我想从主线程中绘制)
而不是使用渲染器和从onDrawFrame内部绘图).我收到错误:“确保SurfaceView或相关的SurfaceHolder具有有效的Surface”.显然mEgl.eglCreateWindowSurface失败,因为surfaceHolder没有有效的表面.如何获得具有有效Surface的SurfaceHolder?

我的Activity.onCreate方法是:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    GLSurfaceView surfaceView = new GLSurfaceView(this);
    setContentView(surfaceView);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    Surface surface = surfaceHolder.getSurface();
    Log.v("HelloAndroid","surface.isValid()= " + Boolean.toString(surface.isValid()));

    EGL10 mEgl = (EGL10) EGLContext.getEGL();
    EGLDisplay mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
    int[] version = new int[2];
    mEgl.eglInitialize(mEglDisplay,version);
    EGLConfig[] configs = new EGLConfig[1];
    int[] num_config = new int[1];
    int[] configSpec = {
            EGL10.EGL_NONE
    };
    mEgl.eglChooseConfig(mEglDisplay,configSpec,configs,1,num_config);
    EGLConfig mEglConfig = configs[0];
    EGLContext mEglContext = mEgl.eglCreateContext(mEglDisplay,mEglConfig,EGL10.EGL_NO_CONTEXT,null);
    EGLSurface mEglSurface = null;
    Log.v("HelloAndroid","M");
    mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,surfaceHolder,null);
    Log.v("HelloAndroid","N");
    mEgl.eglMakeCurrent(mEglDisplay,mEglSurface,mEglContext);
    Log.v("HelloAndroid","O");
}

我使用platform-tools / adb logcat获得的日志输出是:

V/HelloAndroid( 1861): surface.isValid()= false
D/libEGL  ( 1861): egl.cfg not found,using default config
D/libEGL  ( 1861): loaded /system/lib/egl/libGLES_android.so
V/HelloAndroid( 1861): M
D/AndroidRuntime( 1861): Shutting down VM
W/dalvikvm( 1861): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
E/AndroidRuntime( 1861): Uncaught handler: thread main exiting due to uncaught exception
E/AndroidRuntime( 1861): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloandroid/com.example.helloandroid.HelloAndroid}: java.lang.IllegalArgumentException: Make sure the SurfaceView or associated SurfaceHolder has a valid Surface
E/AndroidRuntime( 1861):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)

任何帮助表示赞赏.

解决方法

在创建表面时应该对表面有效的检查.所以,应该在onSurfaceCreated或onSurfaceChanged中调用surface.isValid(),显然,你应该添加surfaceholder.callback

相关文章

以下为个人理解,如错请评 CE: 凭据加密 (CE) 存储空间, 实际路径/data/user_ce/ DE: 设备加密 (DE) 存...
转载来源:https://blog.csdn.net/yfbdxz/article/details/114702144 用EventLog.writeEvent打的日志(或...
事件分发机制详解 一、基础知识介绍 1、经常用的事件有:MotionEvent.ACTION_DOWN,MotionEvent.ACTION...
又是好久没有写博客了,一直都比较忙,最近终于有时间沉淀和整理一下最近学到和解决的一些问题。 最近进...
Android性能优化——之控件的优化 前面讲了图像的优化,接下来分享一下控件的性能优化,这里主要是面向...
android的开源库是用来在android上显示gif图片的。我在网上查了一下,大家说这个框架写的不错,加载大的...