仿微信语音接听黑屏亮屏

xiaoxiao2021-02-28  10

Android系统自带有11种传感器,我们可以通过距离传感器来实现。

创建传感器管理器:

/** * 传感器 */ private SensorManager sm; //设备的电源控制器 private PowerManager mPowerManager; //唤醒锁 private PowerManager.WakeLock mWakeLock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //获取系统服务POWER_SERVICE,返回一个PowerManager对象 mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); //获取PowerManager.WakeLock对象 /** * 参数一是PowerManager提供的的四种唤醒锁 * PARTIAL_WAKE_LOCK * SCREEN_DIM_WAKE_LOCK (level 17 deprecated) * SCREEN_BRIGHT_WAKE_LOCK (level 17 deprecated) * FULL_WAKE_LOCK (level 17 deprecated) */ mWakeLock = this.mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWake"); }

注册监听

@Override protected void onResume() { super.onResume(); Sensor s = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); if (s != null) { sm.registerListener(mSensorListener, s, SensorManager.SENSOR_DELAY_NORMAL); } } /** * 感应器监听 */ private SensorEventListener mSensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float[] its = event.values; if (its != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (its[0] == 0.0) { if (mWakeLock.isHeld()) { return; } else { mWakeLock.acquire(); } } else { if (mWakeLock.isHeld()) { return; } else { mWakeLock.setReferenceCounted(false); mWakeLock.release(); } } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } };

“` 销毁取消注册

@Override protected void onDestroy() { stopSensor(); super.onDestroy(); } /** * 取消注册 */ public synchronized void stopSensor() { if (sm != null) { mWakeLock.release();//释放电源锁 sm.unregisterListener(this);//注销传感器监听 }

}

转载请注明原文地址: https://www.6miu.com/read-1100321.html

最新回复(0)