调整大小和恢复/暂停GLSurfaceView时出现问题

问题描述

我在我的应用中使用GLSurfaceView,最近在调整大小时发现了一个奇怪的行为。最后,我找出了导致应用程序出现问题的原因,并创建了一个简单的示例来重现它。

假设我们有一个FrameLayout,其中包含简单的GLSurfaceView。每次点击GLSurfaceView时,我们都会使用以下代码更改其高度

CyclicIterator<Integer> iterator = CyclicIterator.from(200,300,500);
glView.setonClickListener(v -> {
    glView.getLayoutParams().height = sizeIterator.next();
    glView.requestLayout();
});

一切顺利,直到我们快速将应用程序移至后台,然后使用“概述”按钮(类似于“猴子测试”)回到前台。如果我们足够快地在背景/前景之间切换并重新调整视图的大小,则可能会遇到以下情况:表面上出现一个“死”区域,直到我们再次停止/开始活动,该区域才会更新。

每次gl调用后,我都检查了glGetError,但没有收到任何错误。同时,我在width回调中收到了正确的heightonSurfaceChanged

我尝试重现此行为,并在Nexus 5X和小米Redmi 6A上获得了相同的结果。

更多详细信息

GLSurfaceView配置为:

glView.setEGLContextClientVersion(2);
glView.setRenderer(new Renderer() {
    @Override
    public void onSurfaceCreated(GL10 gl,EGLConfig config) {
        gl.glClearColor(1.0f,0.0f,1.0f);
    }

    @Override
    public void onSurfaceChanged(GL10 gl,int width,int height) {
        gl.glViewport(0,width,height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        gl.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    }
});
glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

作为official documentation says,我们应将生命周期事件通知GLSurfaceView

@Override
protected void onStart() {
    super.onStart();
    glView.onResume();
}

@Override
protected void onStop() {
    glView.onPause();
    super.onStop();
}

但是,在实际应用中,当我们的应用进入后台时,我们还需要保存首选项并释放一些资源和服务(see e.g. camera example from Google)。 我发现,是这些调用导致了我的应用中GLSurfaceView的故障,因此我通过以下方式进行了模拟:

@Override
protected void onResume() {
    super.onResume();

    // Simulate such actions as e.g.:
    // restorePreferences();
    // startCameraThread();
    // openCamera();

    synchronized (this){
        try{
            this.wait(400);
        }catch (InterruptedException ie){
            ie.printstacktrace();
        }
    }
}

@Override
protected void onPause() {

    // Simulate such actions as e.g.:
    // releaseCamera();
    // stopCameraThread();
    // savePreferences();

    synchronized (this){
        try{
            this.wait(400);
        }catch (InterruptedException ie){
            ie.printstacktrace();
        }
    }

    super.onPause();
}

脏溶液

我发现可以通过将GLSurfaceView的可见性切换为GONE并再回到VISIBLE中的onResume解决此故障。

@Override
protected void onResume() {
    super.onResume();
    //...
    glView.setVisibility(View.GONE);
    glView.setVisibility(View.VISIBLE);
    //...
}

但是,显然这不是我想要的解决方案,所以

摘要

我是否错过了与GLSurfaceView一起工作的重要事项,还是仅仅是其实现中的错误

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)