欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年09月20日 08:56:12   作者:路宇  
這篇文章主要為大家詳細(xì)介紹了Android光線傳感器的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Android光線傳感器使用的具體代碼,供大家參考,具體內(nèi)容如下

一、首先是布局頁(yè)面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>

二、在對(duì)應(yīng)的Activity中獲取光線傳感器的值LightSensorActivity,具體注釋已經(jīng)在代碼中給出

public class LightSensorActivity extends AppCompatActivity implements SensorEventListener {
? ? private EditText editText;
? ? //傳感器管理器對(duì)象
? ? 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();
? ? ? ? //第一個(gè)參數(shù):SensorEventListener對(duì)象用this來(lái)指定就可以了
? ? ? ? // 第二個(gè)參數(shù):傳感器對(duì)象 光線傳感器類型的常量:TYPE_LIGHT
? ? ? ? // 第三個(gè)參數(shù):傳感器數(shù)據(jù)的頻率 這里采用適合游戲的頻率
? ? ? ? sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), SensorManager.SENSOR_DELAY_GAME);
? ? }

? ? @Override
? ? protected void onPause() {
? ? ? ? super.onPause();
? ? ? ? sensorManager.unregisterListener(this);
? ? }

? ? //當(dāng)傳感器的值,發(fā)生變化時(shí),回調(diào)的方法
? ? @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("光的強(qiáng)度值:");
? ? ? ? ? ? //添加獲取的傳感器的值
? ? ? ? ? ? stringBuilder.append(values[0]);
? ? ? ? ? ? editText.setText(stringBuilder.toString());
? ? ? ? }
? ? }

? ? //當(dāng)傳感器的精度,發(fā)生變化時(shí),回調(diào)的方法
? ? @Override
? ? public void onAccuracyChanged(Sensor sensor, int accuracy) {

? ? }
}

效果如圖所示:

以上是光線傳感器的簡(jiǎn)單使用。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論