Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
Twitter logo OReilly Book Cover Art
HomeF.A.Q.
Community
Writing Recipes
Login
Reading the Temperature Sensor
Contributed by Rachee Singh 2011-07-31 01:41:17 (updated 2011-09-28 07:27:31)
In Published Edition? Yes
0
Votes
Problem

You need to get temperature values using the temperature sensor.

Solution

Using SensorManager and SensorEventListener to track changes in temperature values detected by the temperature sensor.

Discussion

We need to create an object of SensorManager to use sensors in an application. Then we register a listener with the type of sensor we require. To register the listener we provide the name of the listener, a Sensor object and the type of delay (in this case it is SENSOR_DELAY_FASTEST) to the registerListener method. In this listener, within the overridden onSensorChanged method, we can print the temperature value into a textView named tempVal.

SensorManager sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(temperatureListener, sensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE), SensorManager.SENSOR_DELAY_FASTEST);
private final SensorEventListener temperatureListener = new SensorEventListener(){
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}
	@Override
	public void onSensorChanged(SensorEvent event) {

		tempVal.setText("Temperature is:"+event.values[0]);

	}
};
Comments (0)
Leave a comment
Edit History (5)
There are no (moderator-approved) comments on this recipe yet.