当前位置 : 主页 > 手机开发 > android >

Android光线传感器使用方法详解

来源:互联网 收集:自由互联 发布时间:2023-02-01
本文实例为大家分享了Android光线传感器使用的具体代码,供大家参考,具体内容如下 一、首先是布局页面activity_light_sensor.xml ?xml version="1.0" encoding="utf-8"?LinearLayout xmlns:android="http://sch

本文实例为大家分享了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) {

    }
}

效果如图所示:

以上是光线传感器的简单使用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

上一篇:关于Fragment already added问题的解决方案
下一篇:没有了
网友评论