释放双眼,带上耳机,听听看~!
这个功能可以使用距离传感器来实现
P-Sensor距离感应器,可以感应手机和人体距离。具体使用用途是在通话过程中打开P-Sensor,那么当手机屏幕贴近用户脸部时,就会自动感应出手机和人体距离是多少。当小于某一个值时,就会熄灭屏幕,不再接收用户触摸屏幕事件,从而有效的防止通话过程中误触摸事件的出现。
具体实现代码如下:
public class MainActivity extends Activity implements SensorEventListener{
public static final String TAG = "SensorTest";
private SensorManager sensorManager;
private TextView tv;
private PowerManager localPowerManager = null;// 电源管理对象
private WakeLock localWakeLock = null;// 电源锁
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
tv = (TextView) findViewById(R.id.tv);
localPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
localWakeLock = this.localPowerManager.newWakeLock(32, "hahaha");// 第一个参数为电源锁级别,第二个是日志tag
}
@Override
protected void onResume() {
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
SensorManager.SENSOR_DELAY_UI);
super.onResume();
}
@Override
protected void onPause() {
sensorManager.unregisterListener(this);
super.onPause();
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float[] values = event.values;
switch (event.sensor.getType()) {
case Sensor.TYPE_PROXIMITY:
tv.setText(values[0] + "");
if (values[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(); // 释放设备电源锁
}
break;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
仔细想想,是不是屏幕熄灭的时候需要手机自带的电源~
所以需要加上权限:
效果图我就不贴了,需要真机测试
另外,关于Android权限控制可点击此处查看详细描述