传感器Sensor的使用-距离感应(听筒模式)

时间:2022-02-17 12:45:49

对听筒附近的距离感应装置进行监听-靠近(0),远离(1)

1.需要导入的包

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

2.创建对应的对象

    private SensorManager sm = null;
    private SensorListener listener = null;
    private Sensor sensor = null;

3.给对象赋值

            listener = new SensorListener();
            sm = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
            sensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);//TYPE_PROXIMITY为距离感应,还有其他的一些功能

4.注册和注销

注册:

sm.unregisterListener(listener);

注销:

sm.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_UI);

5.对传感器进行监听

   private final class SensorListener implements SensorEventListener {

        @Override
        public void onSensorChanged(SensorEvent event) {
            float range = event.values[0];
            Log.v(TAG,"test_ onSensorChanged range="+range);
            if (range == 0) {//靠近(0),远离(1)
            }
        }

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

        }
    }

 

相关网页:

http://blog.sina.com.cn/s/blog_6e334dc7010195hc.html

http://blog.sina.com.cn/s/blog_6f3ff2c90100sryp.html

http://www.open-open.com/lib/view/open1386727414970.html