FileDocCategorySizeDatePackage
CompassActivity.javaAPI DocAndroid 1.5 API8482Wed May 06 22:41:08 BST 2009com.example.android.compass

CompassActivity

public class CompassActivity extends android.app.Activity implements android.opengl.GLSurfaceView.Renderer, android.hardware.SensorEventListener
This class provides a basic demonstration of how to use the {@link android.hardware.SensorManager SensorManager} API to draw a 3D compass.

Fields Summary
private android.opengl.GLSurfaceView
mGLSurfaceView
private android.hardware.SensorManager
mSensorManager
private float[]
mGData
private float[]
mMData
private float[]
mR
private float[]
mI
private FloatBuffer
mVertexBuffer
private FloatBuffer
mColorBuffer
private ByteBuffer
mIndexBuffer
private float[]
mOrientation
private int
mCount
Constructors Summary
public CompassActivity()


      
    
Methods Summary
public voidonAccuracyChanged(android.hardware.Sensor sensor, int accuracy)

    
public voidonCreate(android.os.Bundle savedInstanceState)
Called with the activity is first created.

        super.onCreate(savedInstanceState);

        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        mGLSurfaceView = new GLSurfaceView(this);
        mGLSurfaceView.setRenderer(this);
        setContentView(mGLSurfaceView);
    
public voidonDrawFrame(javax.microedition.khronos.opengles.GL10 gl)

        /*
         * Usually, the first thing one might want to do is to clear
         * the screen. The most efficient way of doing this is to use
         * glClear().
         */

        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        /*
         * Now we're ready to draw some 3D objects
         */

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(0, 0, -2);

        /*
         * All the magic happens here. The rotation matrix mR reported by
         * SensorManager.getRotationMatrix() is a 4x4 row-major matrix.
         * We need to use its inverse for rendering. The inverse is
         * simply calculated by taking the matrix' transpose. However, since
         * glMultMatrixf() expects a column-major matrix, we can use mR
         * directly!
         */
        gl.glMultMatrixf(mR, 0);
        // some test code which will be used/cleaned up before we ship this.
        //gl.glMultMatrixf(mI, 0);

        gl.glVertexPointer(3, GL_FLOAT, 0, mVertexBuffer);
        gl.glColorPointer(4, GL_FLOAT, 0, mColorBuffer);
        gl.glDrawElements(GL_LINES, 6, GL_UNSIGNED_BYTE, mIndexBuffer);
    
protected voidonPause()

        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onPause();
        mGLSurfaceView.onPause();
        mSensorManager.unregisterListener(this);
    
protected voidonResume()

        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onResume();
        mGLSurfaceView.onResume();
        Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME);
        mSensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME);
    
public voidonSensorChanged(android.hardware.SensorEvent event)

        int type = event.sensor.getType();
        float[] data;
        if (type == Sensor.TYPE_ACCELEROMETER) {
            data = mGData;
        } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
            data = mMData;
        } else {
            // we should not be here.
            return;
        }
        for (int i=0 ; i<3 ; i++)
            data[i] = event.values[i];

        SensorManager.getRotationMatrix(mR, mI, mGData, mMData);
// some test code which will be used/cleaned up before we ship this.
//        SensorManager.remapCoordinateSystem(mR,
//                SensorManager.AXIS_X, SensorManager.AXIS_Z, mR);
//        SensorManager.remapCoordinateSystem(mR,
//                SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, mR);
        SensorManager.getOrientation(mR, mOrientation);
        float incl = SensorManager.getInclination(mI);

        if (mCount++ > 50) {
            final float rad2deg = (float)(180.0f/Math.PI);
            mCount = 0;
            Log.d("Compass", "yaw: " + (int)(mOrientation[0]*rad2deg) +
                    "  pitch: " + (int)(mOrientation[1]*rad2deg) +
                    "  roll: " + (int)(mOrientation[2]*rad2deg) +
                    "  incl: " + (int)(incl*rad2deg)
                    );
        }
    
public voidonSurfaceChanged(javax.microedition.khronos.opengles.GL10 gl, int width, int height)

        gl.glViewport(0, 0, width, height);

        /*
         * Set our projection matrix. This doesn't have to be done
         * each time we draw, but usually a new projection needs to
         * be set when the viewport is resized.
         */

        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
    
public voidonSurfaceCreated(javax.microedition.khronos.opengles.GL10 gl, javax.microedition.khronos.egl.EGLConfig config)

        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        gl.glDisable(GL10.GL_DITHER);

        /*
         * Some one-time OpenGL initialization can be made here
         * probably based on features of this particular context
         */
        gl.glClearColor(1,1,1,1);
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glShadeModel(GL10.GL_SMOOTH);
        gl.glEnable(GL10.GL_DEPTH_TEST);

        /*
         * create / load the our 3D models here
         */

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        float vertices[] = {
                0,0,0,
                1,0,0,
                0,1,0,
                0,0,1
        };
        float colors[] = {
                0,0,0,0,
                1,0,0,1,
                0,1,0,1,
                0,0,1,1
        };
        byte indices[] = { 0, 1, 0, 2, 0, 3 };

        // Buffers to be passed to gl*Pointer() functions
        // must be direct, i.e., they must be placed on the
        // native heap where the garbage collector cannot
        // move them.
        //
        // Buffers with multi-byte datatypes (e.g., short, int, float)
        // must have their byte order set to native order

        ByteBuffer vbb;
        vbb = ByteBuffer.allocateDirect(vertices.length*4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();
        mVertexBuffer.put(vertices);
        mVertexBuffer.position(0);

        vbb = ByteBuffer.allocateDirect(colors.length*4);
        vbb.order(ByteOrder.nativeOrder());
        mColorBuffer = vbb.asFloatBuffer();
        mColorBuffer.put(colors);
        mColorBuffer.position(0);

        mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
        mIndexBuffer.put(indices);
        mIndexBuffer.position(0);