Check the state of a sensor

  1. Import the required classes and interfaces.
    import net.rim.device.api.system.Sensor;
  2. Invoke Sensor.getState() and specify the type of sensor that you want to check. The sensor types are defined as constants in the Sensor class. The following code sample checks the state of the slider on a BlackBerry® device.
    int sliderState = Sensor.getState(Sensor.SLIDE);
    The method returns the sensor's state as an int constant. The constants that can be returned are defined in the Sensor class. You can use the following methods to determine whether the sensor is in a given state: Sensor.isSlideClosed(), Sensor.isSlideOpen(), Sensor.isSlideInTransition().

Code sample: Displaying the state of the device's slider

class SensorDemoScreen extends MainScreen implements SensorListener
{
    private RichTextField statusField;
    
    public SensorDemoScreen()
    {   
        setTitle("Sensor Demo");
        statusField = new RichTextField();
        add(statusField);

        if (Sensor.isSupported(Sensor.SLIDE))
        {
            int sliderState = Sensor.getState(Sensor.SLIDE);
            
            switch (sliderState)
            {
                case Sensor.STATE_SLIDE_CLOSED:
                    // do something if slider is closed
                    statusField.setText("Slider is closed.");
                    break;
                case Sensor.STATE_SLIDE_IN_TRANSITION:
                    // do something if slider in transition
                    statusField.setText("Slider is between open and closed.");
                    break;
                case Sensor.STATE_SLIDE_OPEN:
                    // do something if slider is open
                    statusField.setText("Slider is open.");
                    break;
                default:
                    statusField.setText("Can't determine state of slider.");
            }
        }
    }
}

Was this information helpful? Send us your comments.