Detect if the BlackBerry smartphone is holstered or flipped

by BlackBerry Development Advisor ‎02-12-2010 04:35 PM - edited ‎02-17-2010 10:27 AM (1,821 Views)

Summary


This article applies to the following:

  • BlackBerry® application programming interface (API) set 4.6 or later
  • BlackBerry® Device Software 4.6 or later


Details


The Sensor API allows third-party applications to query the existence and states of BlackBerry smartphone sensors (for example, holster or flip). This API also supports registration to a SensorListener that can receive updates for specified sensor(s).


Note: The relevant classes added to BlackBerry® Java® Development Environment (BlackBerry JDE) 4.6 are as follows:


  • net.rim.device.api.system.Sensor
  • net.rim.device.api.system.SensorListener

Procedure


The following code snippet shows how to receive sensor updates for both flip and holster events using the SensorListener:



public class SensorDemo extends Application implements SensorListener {



public SensorDemo() {
Sensor.addListener(this,this,Sensor.HOLSTER | Sensor.FLIP);
System.exit(0);
}

public void onSensorUpdate(int sensorId, int update)
{
switch(sensorId)
{
case Sensor.HOLSTER:
System.out.println("Received an Holster update!");
switch(update){
case Sensor.STATE_IN_HOLSTER:
System.out.println("Device Holstered!");
break;
case Sensor.STATE_OUT_OF_HOLSTER:
System.out.println("Device out of Holster!");
break;
default:
System.out.println("Unknown Holster update");

}
break;

case Sensor.FLIP:
System.out.println("Received a Flip update!");
switch(update){
case Sensor.STATE_FLIP_OPEN:
System.out.println("Device Flip opened!");
break;
case Sensor.STATE_FLIP_CLOSED:
System.out.println("Device Flip closed!");
break;
default:
System.out.println("Unknown Flip update");

}
break;
default;
}
}

public static void main(String[] args)
{
new SensorDemo().enterEventDispatcher();
}