Android temperature sensor

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 the temperature from the device.

I wrote this code and I tried it on HTC One X, but it did not work.

+7
source share
2 answers

As long as the htc one x spec says, this device does not seem to have a temperature sensor.

Take a look at the official specs.

+6
source

Currently, only a few devices have a temperature sensor (for example, Samsung S4).

You should always check if the sensor is available, i.e. {

 temperatureSensor = sensormanager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) if (temperatureSensor != null) { /* register listener and do other magic... */ } 

What you can do on HTC is to find another thermistor in the system and read the sysfs path where its value is displayed, for example, a thermistor in the battery or pressure sensor, if there is one in this phone.

The disadvantage of this approach is that these are the initial thermistor values ​​- sometimes you need to know how to convert them to degrees Celsius, and worse, they are not compensated (because the temperature is from the API) - for example, if the phone does some calculations and the processor heats up the phone, this value can easily be 10 degrees higher than the ambient temperature and therefore not very useful ...

+1
source

All Articles