Temperature sensor on Android

Furkan picture Furkan · Aug 14, 2012 · Viewed 11k times · Source
 public class MainActivity extends Activity implements SensorEventListener {
    private TextView temperaturelabel;
    private SensorManager sensormanager;
    private Sensor temperature;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    temperaturelabel = (TextView) findViewById(R.id.text);

    sensormanager = (SensorManager)getSystemService(SENSOR_SERVICE);

    temperature= sensormanager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);

   temperaturelabel.setText(""+temperature.getPower());
 }

 protected void onResume() {
     super.onResume();
     sensormanager.registerListener(this, temperature, SensorManager.SENSOR_DELAY_FASTEST);
 }

 protected void onPause() {                 
     super.onPause();
     sensormanager.unregisterListener(this);
 }

 public void onAccuracyChanged(Sensor sensor, int accuracy) {}

 public void onSensorChanged(SensorEvent event) {   
        if (event.sensor.getType() != Sensor.TYPE_AMBIENT_TEMPERATURE) return;

        temperaturelabel.setText(""+temperature.getPower());
    }
 }

I want to get temperature from the device.

I wrote this code and I have tried it on HTC One X, but it didn't work.

Answer

Jviaches picture Jviaches · Aug 14, 2012

A far as specification of htc one x says, its looks like this device doesn't have temperature sensor.

Take a look in its official specifications.