Android Proximity Sensor近距离传感器P-Sensor

package zhangphil.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private SensorManager mSensorManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        startSensor();
    }

    /**
     * 启动传感器。
     */
    private void startSensor() {
        mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
        Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

        if (mSensorManager == null || mSensor == null) {
            throw new UnsupportedOperationException("设备不支持");
        }

        boolean isRegister = mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        if (!isRegister) {
            throw new UnsupportedOperationException("设备不支持");
        }
    }

    private SensorEventListener mSensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float proximity=sensorEvent.values[0];
            Log.d("近距离", String.valueOf(proximity));
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mSensorEventListener);
    }
}

上一篇:.Net5,C#9 新语法(逻辑和属性模式,记录)


下一篇:fixture.detectChange开始单步调试,如何执行到Directive的ngAfterViewInit钩子