Notify an application when the state of a sensor changes
-
Import the required classes and interfaces.
import net.rim.device.api.system.Sensor;
import net.rim.device.api.system.SensorListener;
-
Create a class that implements the
SensorListener interface.
class SensorDemoScreen extends MainScreen implements SensorListener
{
}
-
In the class, implement
SensorListener.onSensorUpdate() and perform actions
based on the type of sensor (the method's first parameter) and the new state of
the sensor (the second parameter). The following code sample checks the state
of the slider on a
BlackBerry®
device.
public void onSensorUpdate(int sensorID, int update)
{
if (sensorID == Sensor.SLIDE)
{
if (update == Sensor.STATE_SLIDE_OPEN)
{
// do something if slider is now open
statusField.setText("Slider is now open.");
}
else if (update == Sensor.STATE_SLIDE_IN_TRANSITION)
{
// do something if slider is now in transition
statusField.setText("Slider state is now in transition.");
}
else if (update == Sensor.STATE_SLIDE_CLOSED)
{
// do something if slider is now closed
statusField.setText("Slider is now closed.");
}
}
}
-
Invoke
SensorListener.addListener() to add the listener to
your application. Specify the application, the listener to add, and the types
of sensor changes to listen for. The following code sample adds a listener for
slider changes to the current application. You can invoke
Sensor.removeListener() to remove a listener.
Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE);
-
To listen for changes to multiple sensors, update the third
argument of
addListener() to add additional sensor state flags.
The following code sample listens for changes to the flip sensor or slider
sensor.
Sensor.addListener(Application.getApplication(), this, Sensor.FLIP | Sensor.SLIDE);
Code sample: Listening for changes to 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);
Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE);
}
public void onSensorUpdate(int sensorID, int update)
{
if (sensorID == Sensor.SLIDE)
{
if (update == Sensor.STATE_SLIDE_OPEN)
{
// do something if slider is now open
statusField.setText("Slider is now open.");
}
else if (update == Sensor.STATE_SLIDE_IN_TRANSITION)
{
// do something if slider is now in transition
statusField2.setText("Slider state is now in transition.");
}
else if (update == Sensor.STATE_SLIDE_CLOSED)
{
// do something if slider is now closed
statusField.setText("Slider is now closed.");
}
}
}
}
Was this information helpful? Send us your comments.