Sensing Magnetic Fields in Android in Very Few Lines!

Overcome with gadget lust, I picked up a HTC Dream from rogers. I had fully expected to need to unlock, root, resolder or otherwise hack this thing to pieces before it could do anything interesting. I was wrong. So wrong.

I'll gush more over the particulars of the phone dreaminess in another post, I hope. It can pretty much do anything I do on my laptop, except with exponentially higher rates of thumb cramping. But I digress. There are magnetic fields to sense.

I figured that it was time for a Hello-Worldy style application. Dredging through the docs, I found some interesting class names, sullenly quit emacs and fired up eclipse.

My goal here was to simply display the state of the magnetic field sensor as it updated. I figured a compassy thing would be pretty easy to cook up. Here's the first step in getting that going.

HelloTest.java

public class HelloTest extends Activity {
       
        @Override
       
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SensingTextView tv = new SensingTextView(this);
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        sm.registerListener(tv,
                        sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                        SensorManager.SENSOR_DELAY_UI);
        setContentView(tv);
    }
}

And here's the SensingTextView:
SensingTextView.java

public class SensingTextView extends TextView implements SensorEventListener {
        public SensingTextView(Context context) {
                super(context);
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        public void onSensorChanged(SensorEvent event) {
                String newstr = String.format("x: %f\ny:%f\nz:%f",
                                   new Object[] { event.values[0],event.values[1],event.values[2] } );
                setText(newstr);
        }

}

3 thoughts on “Sensing Magnetic Fields in Android in Very Few Lines!”

  1. Hi, very good post. I have one question. Is it possible to use magnetic field to count strength in nanoteslas.

Leave a Reply

Your email address will not be published. Required fields are marked *