这篇文章主要为大家详细介绍了Android光线传感器的使用方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Android光线传感器使用的具体代码,供大家参考,具体内容如下
一、首先是布局页面activity_light_sensor.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".LightSensorActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center"
android:text="光线传感器"
android:textColor="@color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>二、在对应的Activity中获取光线传感器的值LightSensorActivity,具体注释已经在代码中给出
public class LightSensorActivity extends AppCompatActivity implements SensorEventListener {
private EditText editText;
//传感器管理器对象
private SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_sensor);
editText = findViewById(R.id.editText);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
//第一个参数:SensorEventListener对象用this来指定就可以了
// 第二个参数:传感器对象 光线传感器类型的常量:TYPE_LIGHT
// 第三个参数:传感器数据的频率 这里采用适合游戏的频率
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
//当传感器的值,发生变化时,回调的方法
@Override
public void onSensorChanged(SensorEvent event) {
//获取传感器的值
float[] values= event.values;
//获取传感器类型
int sensorType = event.sensor.getType();
StringBuilder stringBuilder = null;
if (sensorType==Sensor.TYPE_LIGHT){
stringBuilder = new StringBuilder();
stringBuilder.append("光的强度值:");
//添加获取的传感器的值
stringBuilder.append(values[0]);
editText.setText(stringBuilder.toString());
}
}
//当传感器的精度,发生变化时,回调的方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}效果如图所示:
以上是光线传感器的简单使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:Android光线传感器使用方法详解
猜你喜欢
- Android实现轮询的三种方式 2023-02-17
- Android studio实现动态背景页面 2023-05-23
- 详解flutter engine 那些没被释放的东西 2022-12-04
- 最好用的ios数据恢复软件:PhoneRescue for Mac 2023-09-14
- SurfaceView播放视频发送弹幕并实现滚动歌词 2023-01-02
- 作为iOS开发,这道面试题你能答出来,说明你基础很OK! 2023-09-14
- Android MaterialButton使用实例详解(告别shape、selector) 2023-06-16
- iOS 对当前webView进行截屏的方法 2023-03-01
- Android实现监听音量的变化 2023-03-30
- Flutter实现底部和顶部导航栏 2022-08-31
