Android传感器(四):距离传感器
2019-07-13 23:03发布
生成海报
距离传感器应用之一通话时手机屏的亮灭
private PowerManager localPowerManager = null;
private PowerManager.WakeLock localWakeLock = null;
setContentView(R.layout.activity_main)
//初始化距离传感器
initSensor(this,Sensor.TYPE_PROXIMITY)
setOnChangeListener(this)
localPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE)
// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
localWakeLock = this.localPowerManager.newWakeLock(32, "MyPower")
float[] its = event.values
//Log.d(TAG,"its array:"+its+"sensor type :"+event.sensor.getType()+" proximity type:"+Sensor.TYPE_PROXIMITY)
if (its != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
// System.out.println("its[0]:" + its[0])
// tv.setText(its[0]+"")
//经过测试,当手贴近距离感应器的时候its[0]返回值为0.0,当手离开时返回1.0
if (its[0] == 0.0) {// 贴近手机
// System.out.println("hands up")
Log.d(TAG,"hands up in calling activity")
if (localWakeLock.isHeld()) {
return
} else{
localWakeLock.acquire()
}
} else {// 远离手机
System.out.println("hands moved")
Log.d(TAG,"hands moved in calling activity")
if (localWakeLock.isHeld()) {
return
} else{
localWakeLock.setReferenceCounted(false)
localWakeLock.release()
}
}
}
- 重点:销毁activity时需要释放电源锁,如果不释放,finish这个acitivity后仍然会有自动锁屏的效果,即使取消传感器监听,依然有锁频效果,没想明白
@Override
public void onDestroy(){
super.onDestroy();
Log.d(TAG,"on destroy");
if(localWakeLock != null){
localWakeLock.release();
}
}
Demo下载:
gingerbread
相关链接:
我的Android开发相关文章
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮