Code sample: Polling for magnetometer data

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.system.MagnetometerListener;
import net.rim.device.api.system.MagnetometerChannelConfig;
import net.rim.device.api.system.MagnetometerData;
import net.rim.device.api.system.MagnetometerSensor;
import net.rim.device.api.system.MagnetometerSensor.Channel;
import net.rim.device.api.ui.component.Dialog;


public class MagPoll extends UiApplication implements Runnable
{
    private DataScreen _scrData;
    private boolean bRunning = true;
    
    public static void main(String[] args)
    {
        MagPoll app = new MagPoll();
        app.enterEventDispatcher();
    }
    
    public MagPoll()
    {
        _scrData = new DataScreen();
        pushScreen(_scrData);
        Thread poller = new Thread(this);
        poller.start();
    }
    
    public void run()
    {
     Channel magChannel = MagnetometerSensor.openChannel(Application.getApplication());
     
     while( bRunning ) 
					{
         double direction = 0;
         MagnetometerData data = magChannel.getData();
         synchronized( data ) 
         {
             direction = data.getDirection(MagnetometerData.MAGNETOMETER_GET_DIRECTION_TOP);
         }    
         _scrData.displayData(direction);

         try
         {
            Thread.sleep( 500 );
         }
         catch(Exception e)
         {
             //handle exception
         }
     }
     magChannel.close();
    }
}

class DataScreen extends MainScreen
{
    LabelField _labelMagDir;
    
    public DataScreen()
    {
        _labelMagDir = new LabelField("No data yet.");
        add(_labelMagDir);
    }
    
				void displayData(double direction)
    {
        synchronized(UiApplication.getUiApplication().getEventLock())
        {
            _labelMagDir.setText(Double.toString(direction));
        }
    } 
}

Was this information helpful? Send us your comments.