Sensor(LIGHT)

package com.example.sensor01;

import java.util.List;

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

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager mSensorManager;
    private TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textview = (TextView) findViewById(R.id.content);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        
        //光线感应传感器检测实时的光线强度,光强单位是lux,值越低,越暗
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

        mSensorManager.registerListener(this, sensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        float light = 0;

        if (event.sensor.getType() == Sensor.TYPE_LIGHT) {

            light = event.values[0];
        }

        textview.setText(String.valueOf(light));

    }
}

 

你可能感兴趣的:(sensor)