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());
}
}
我想从设备中获取温度。
我编写了这段代码,并在 HTC One X 上尝试过,但没有成功。