Sensor Hacking

So let us dig into the juicy bits! A google search on “android sensor orientation” turned up a promising result from ibm. At a glance it has some code that looks simple enough to explore.

We wanna keep our package declaration and MainActivity class so we copy-paste from

implements SensorListener {

and onwards. With a bit of tweaking our task is to get it up and running on our phone. We look at the warnings and errors and solve each of them one at a time – using internet if we get stuck. There is a 99.99% chance that someone else already have the problem you are right now facing. This is what I refer to as Modern Debugging 🙂

Now, the first thing we notice is a cascade of warnings and errors. To get rid of those we need to do quite a few things:

1. Create and name the missing textViews in the layout.xml file

2. The SensorListener is deprecated and should be replaced by SensorEventListener

3. Unimplemented and changed functions (e.g. events rather than direct values)

4. The changed declaration of registerListener.

After the changes it should look something like this:


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class Main extends Activity implements SensorEventListener {
    final String tag = "IBMEyes";
    SensorManager sm = null;
    TextView xViewO = null;
    TextView yViewO = null;
    TextView zViewO = null;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        // get reference to SensorManager
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        xViewO = (TextView) findViewById(;
        yViewO = (TextView) findViewById(;
        zViewO = (TextView) findViewById(;
	            sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD ),
    public void onSensorChanged(SensorEvent event) {
        synchronized (this) {
            if (event.sensor.getType() == SensorManager.SENSOR_MAGNETIC_FIELD) {
                xViewO.setText("Magnetic X: " + event.values[0]);
                yViewO.setText("Magnetic Y: " + event.values[1]);
                zViewO.setText("Magnetic Z: " + event.values[2]);
    public void onAccuracyChanged(int sensor, int accuracy) {
    	Log.d(tag,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
    protected void onResume() {
        // register this class as a listener for the 
        // orientation and accelerometer sensors
    protected void onStop() {
        // unregister listener
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

This should now run on the device and put out values from the magnetometer to the screen.