Code sample: Creating and registering a magnetometer listener

import net.rim.device.api.ui.UiApplication;
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.*;


public class MagListener extends UiApplication implements MagnetometerListener
{
    private DataScreen _scrData;
    
    public static void main(String[] args)
    {
        MagListener app = new MagListener();
        app.enterEventDispatcher();
    }
    
    public MagListener()
    {
        _scrData = new DataScreen();
        pushScreen(_scrData);
        
        Channel  magChannel = MagnetometerSensor.openChannel(this);
        magChannel.addMagnetometerListener(this);
    }
    
    public void onData(MagnetometerData magData)
    {
        _scrData.displayData(magData);
    }
}



class DataScreen extends MainScreen
{
    LabelField _labelMagStrength;
    
    public DataScreen()
    {
        _labelMagStrength = new LabelField("No data yet.");
        add(_labelMagStrength);
    }
    
    void displayData(MagnetometerData magData)
    {
        _labelMagStrength.setText(Float.toString(magData.getFieldStrength()));
    }
    
}
Previous topic: Code samples

Was this information helpful? Send us your comments.