android stduio检测温湿度的代码
时间: 2024-02-04 13:00:43 浏览: 211
stm32课程设计,stm32f103c8t6,温湿度检测多功能模块,HAL库+源代码+文档说明
在Android Studio中检测温湿度的代码可以通过传感器来实现。首先,需要在AndroidManifest.xml文件中添加权限:
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```
然后,在MainActivity.java中编写代码来获取温湿度传感器的数据:
```java
package com.example.temphumiditysensor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor tempSensor;
private Sensor humidSensor;
private TextView tempText;
private TextView humidText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempText = findViewById(R.id.tempTextView);
humidText = findViewById(R.id.humidTextView);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
humidSensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, tempSensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, humidSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
float tempValue = event.values[0];
tempText.setText("Temperature: " + tempValue + " °C");
} else if (event.sensor.getType() == Sensor.TYPE_RELATIVE_HUMIDITY) {
float humidValue = event.values[0];
humidText.setText("Humidity: " + humidValue + " %");
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something if accuracy changes
}
}
```
在activity_main.xml中添加TextView来显示温度和湿度的数值:
```xml
<TextView
android:id="@+id/tempTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature: "
android:textSize="18sp" />
<TextView
android:id="@+id/humidTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Humidity: "
android:textSize="18sp" />
```
通过以上代码,我们可以在Android设备上实时获取温湿度传感器的数据,并显示在界面上。
阅读全文