Android OpenGL ES RENDERMODE_WHEN_DIRTY implementation

| | August 11, 2015

I am trying to understand RENDERMODE_WHEN_DIRTY so that I could save battery life wherever possible.. I made this sample application so that GlSurfaceView is updated with random color only when the random number temp is greater than 50… If the value of temp is less than 50, I want it to retain the last random color.. But in this code sample, it is not retaining it but making the screen go black forever!

Basically I want to know if my implementation of RENDERMODE_WHEN_DIRTY correct…

package com.blob.blob;

import java.util.Random;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;

public class OpenGLActivity extends Activity implements Renderer
{
    GLSurfaceView glView;
    Random rand ;
    @Override
    public void onCreate(Bundle s)
    {
        super.onCreate(s);
        glView = new GLSurfaceView(this);
        glView.setRenderer(this);
        glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        rand = new Random();
        setContentView(glView);

    }

    public void onDrawFrame(GL10 gl) 
    {           
        int temp = rand.nextInt(100);

        if(temp > 50)
        {
        glView.requestRender();

        gl.glClearColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat(), 1);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        }       

    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {

        Log.d("OpenglTest", "Surface Changed");
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        Log.d("OpenglTest", "Surface Created");
    }

    public void onPause()
    {

        super.onPause();
        glView.onPause();


    }


    public void onResume()
    {       
        super.onResume();
        glView.onResume();
    }
}

One Response to “Android OpenGL ES RENDERMODE_WHEN_DIRTY implementation”

  1. RENDERMODE_WHEN_DIRTY means “do not call onDrawFrame() unless something explicitly requests rendering with requestRender()“. Your code snippet is calling requestRender() from within onDrawFrame(), so nothing will ever happen.

    The idea behind requestRender() is that nothing is drawn until some other thread has decided that rendering needs to happen. The SurfaceView docs note that it “may be called from any thread”, which is necessary for this method to have any value, because the renderer thread is just sitting there waiting for somebody to wake it up.

Leave a Reply