這一片篇介紹如何讀手機上的光感測器,

Android有關於環境感測器資料擷取,包含環境溫度、光、壓力、濕度,以及裝置溫度感測器,如下表所列:

Sensor Sensor event data Units of measure Data description
TYPE_AMBIENT_TEMPERATURE event.values[0] °C Ambient air temperature.
TYPE_LIGHT event.values[0] lx Illuminance.
TYPE_PRESSURE event.values[0] hPa or mbar Ambient air pressure.
TYPE_RELATIVE_HUMIDITY event.values[0] % Ambient relative humidity.
TYPE_TEMPERATURE event.values[0] °C Device temperature.1

1 Implementations vary from device to device. This sensor was deprecated in Android 4.0 (API Level 14).

以下為取得光感測器的Android code:

package com.example.light_sensor;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class LightSensorActivity extends Activity implements SensorEventListener{
    
    private SensorManager mysensorManager;
    private Sensor lsensor;
    private TextView lsensor_lx;
    private static final String TAG = "sensor";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light_sensor);
        lsensor_lx = (TextView)this.findViewById(R.id.ls_lx);
        //Get an instance of the sensor service, and use that to get an instance of a particular sensor.
        mysensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        lsensor = mysensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

    }
    @Override
    public final void onAccuracyChanged(Sensor sensor, int accuracy) {
      // Do something here if sensor accuracy changes.
    }

    @Override
    public final void onSensorChanged(SensorEvent event) {
      float light_value = event.values[0];
      // Do something with this sensor data.
      lsensor_lx.setText("Light:"+ String.valueOf(light_value)+"lux");
      Log.i(TAG,"\n lux" + light_value);
    }

    @Override
    protected void onResume() {
      // Register a listener for the sensor.
      super.onResume();
      mysensorManager.registerListener(this, lsensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
      // Be sure to unregister the sensor when the activity pauses.
      super.onPause();
      mysensorManager.unregisterListener(this);
    }
}

手機畫面:

Screenshot_2016-07-08-09-35-52.jpg

參考資料:

1. https://developer.android.com/guide/topics/sensors/sensors_overview.html

2. https://developer.android.com/guide/topics/sensors/sensors_environment.html#sensors-using-temp

文章標籤
創作者介紹
創作者 fishark 的頭像
fishark

魚的方舟 * 圖形語言的世界* - LabVIEW 工作室 & APP開發研究室 & Arduino整合開發 -

fishark 發表在 痞客邦 留言(0) 人氣()