Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

運用光線感測器即時顯示當前光照強度

編輯:關於 Android 開發

運用光線感測器即時顯示當前光照強度

大多數智慧型手機都內建了光線感測器(Ambient Light Sensor),可偵測環境亮度並據此自動調整螢幕背光。本文示範如何透過 SensorManager 讀取這項資料,並即時顯示於畫面上,單位為勒克斯(Lux)。

一、MainActivity.java

package com.example.guangzhao;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;

public class MainActivity extends Activity {

private SensorManager sensorManager;
private TextView lightLevel;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lightLevel = (TextView) findViewById(R.id.light);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(listener);
}
}

private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float value = event.values[0];
lightLevel.setText("當前光照強度為" + value + "勒克斯");
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}

二、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"/>
</RelativeLayout>

關鍵在於透過 getDefaultSensor(Sensor.TYPE_LIGHT) 取得光線感測器,並在 onSensorChanged 回呼中讀取 event.values[0],該值即為當前環境的光照強度。別忘了在 onDestroy 中取消註冊,以釋放資源並節省電力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved