这次写的是安卓的高级开发篇中简单的传感器内容,每个手机都有一定的传感器内容 ,如何去使用和开发这是我必要走的一条"秃头"之路!!!
这下面是安卓几个传感器 我本太懒 只能拍照片了 朋友们可以参考学习.
代码来了 将代码方法MainActivity里面 (本人用java写的) 特意代码长度写少点 手机用户方便阅读和研究
package com.android.qqcunchu;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//成员变量 局部变量创建成员变量使用的快捷键 ctrl + alt + f
private TextView contentTv;
private SensorManager sensorManager;
//生命周期onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//运行寻找主组件方法
initViiew();
//运行寻找传感器的方法
findSensorManager();
}
//穿件传感器的方法
private void findSensorManager() {
//获取传感器管理器
sensorManager = (SensorManager) getSystemService
(Context.SENSOR_SERVICE);
//获取手机的所有的传感器
List<Sensor> allSensors = sensorManager.
getSensorList(Sensor.TYPE_ALL);
//创建一个StringBuffer的对象
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("当前手机的数目" +
allSensors.size() + "个数");
//用增强for循环遍历出来
for (Sensor sensor : allSensors) {
//用switch识别传感器
switch (sensor.getType()) {
case Sensor.TYPE_LIGHT:
stringBuffer.append("光传感器");
break;
case Sensor.TYPE_PROXIMITY:
stringBuffer.append("距离传感器");
break;
case Sensor.TYPE_PRESSURE:
stringBuffer.append("气压传感器");
break;
default:stringBuffer.append(sensor.
getType()+
"其他传感器");
}
stringBuffer.append("设备供应商" + sensor.
getVendor() +
"\n 版本号 :" + sensor.getVersion()
+ "\n--\n");
}
contentTv.setText(stringBuffer.toString());
}
//定义扫描组件的动态
private void initViiew() {
contentTv = findViewById(R.id.act_mian_content_tv);
}
}
接下来是layout中的文件 我写的比较简单
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/act_mian_content_tv"
tools:ignore="MissingConstraints">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
喜欢咱何院长 如果你遇到解决不了的问题 说明你正在成长…
大家可以一起学习呀 冲冲冲