1.Sensor.TYPE_PROXIMITY
距离传感器
使用步骤:
1.实现接口重写方法
implements SensorEventListener
实现方法
2.获取传感器服务
//定义传感器管理private SensorManager sensorManager;
//获取传感器服务sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
3.注册传感器监听
@Overrideprotected void onResume() {super.onResume();//注册距离传感器监听sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),SensorManager.SENSOR_DELAY_UI);}
4.根据传感器的值改变情况来监听
@Overridepublic void onSensorChanged(SensorEvent event) {float[] values=event.values;//获取距离传感器的类型int sensorType=event.sensor.getType();//获取传感器类型if (sensorType==Sensor.TYPE_PROXIMITY){if (values[0]==0.0){//贴近手机的状态if (localWakeLock.isHeld()){//锁屏状态是否开启}else {localWakeLock.acquire();//申请电源锁,处于锁屏状态}soundPool.play(soundId,1,1,0,0,1);//播放音效}else {localWakeLock.setReferenceCounted(false);//不使用计数功能localWakeLock.release();//解除锁屏状态}}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}
}
5.注销传感器监听
@Overrideprotected void onDestroy() {super.onDestroy();sensorManager.unregisterListener(this);//注销传感器的监听}