6

I want to get temperature from device. but I don t know how I can do. please help me writing simple. thanks.

Furkan
  • 428
  • 3
  • 5
  • 19
  • Refer to this question: http://stackoverflow.com/questions/6985396/is-there-any-android-api-to-find-sense-room-temperature-programmatically-in-andr – mudit Aug 13 '12 at 09:43

1 Answers1

14

You can use TYPE_AMBIENT_TEMPERATURE for battery or CPU temperature. TYPE_TEMPERATURE is the depcrecated constant.

The modified version of code available at documentation should be like this:

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class TempSensorActivity extends Activity, implements SensorEventListener {
 private final SensorManager mSensorManager;
 private final Sensor mTempSensor;

 public TempSensorActivity() {
     mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
     mTempSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
 }

 protected void onResume() {
     super.onResume();
     mSensorManager.registerListener(this, mTempSensor, SensorManager.SENSOR_DELAY_NORMAL);
 }

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

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

 public void onSensorChanged(SensorEvent event) {
 }
}

Look at sensor documentation for more.

Fortran
  • 2,218
  • 2
  • 27
  • 33
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • This is very helpful but there's a more complete answer here: https://stackoverflow.com/a/29285300/1617737 – ban-geoengineering Aug 18 '17 at 10:39
  • 2
    Why do system return null for mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) on every device that I test? Other apps display the temperature on the same device. How it is possible? For example, I use Samsung S9 and system returns null too. – Ponomarenko Oleh Mar 28 '19 at 11:28
  • Same null problem as @PonomarenkoOleh ... any one solved this issue? – Ayush Katuwal Sep 10 '20 at 11:37