Android: get values of the Temperature Sensor, show them on the display

Mainactivity.java:

[code]

public class MainActivity extends AppCompatActivity implements SensorEventListener {

private SensorManager mSM;
private Sensor mTemp;
private TextView sensorTextView;

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

sensorTextView = findViewById(R.id.sensorTextview);
mSM = (SensorManager) getSystemService(SENSOR_SERVICE);
mTemp = mSM.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
}

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

float tmpval = sensorEvent.values[0];
sensorTextView.setText("Temp :" + (tmpval) );

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override
protected void onResume() {
super.onResume();
mSM.registerListener(this, mTemp, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
super.onPause();
mSM.unregisterListener(this);

}

}

[/code]

activity_main.xml:

[code]
<pre><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/sensorTextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout></pre>
[/code]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.