Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android Apps
GitHub logo Twitter logo OReilly Book Cover Art
Reading the Temperature SensorBack to Android Cookbook Home | Up to Chapter: Accelerometer and other Sensors

Author: Rachee Singh ('racheesingh')
In Published Edition? Yes
FormatLanguage: WikiFormat

Reading the Temperature Sensor

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]);

	}
};

See Also

Checking for the Presence or Absence of a Sensor