日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android光線傳感器使用方法詳解_Android

作者:路宇 ? 更新時間: 2022-11-10 編程語言

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

? ? }
}

效果如圖所示:

以上是光線傳感器的簡單使用。

原文鏈接:https://blog.csdn.net/lu202032/article/details/122029687

欄目分類
最近更新