我的应用程序是拨号器,当用户将手机靠近他的头时,我需要关闭屏幕并防止点击控件 - 就像本机Android拨号器行为一样。我需要什么API级别以及如何以正确的方式执行此操作?
答案 0 :(得分:41)
我通过拆卸一个非常着名的VoIP应用程序找到了解决方案。按下button1后此活动将在关闭传感器时禁用屏幕和硬件键。按下按钮2后,此功能将关闭。
此外,此功能需要权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
活动。试试吧。
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
private int field = 0x00000020;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// Yeah, this is hidden field.
field = PowerManager.class.getClass().getField("PROXIMITY_SCREEN_OFF_WAKE_LOCK").getInt(null);
} catch (Throwable ignored) {
}
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(field, getLocalClassName());
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!wakeLock.isHeld()) {
wakeLock.acquire();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(wakeLock.isHeld()) {
wakeLock.release();
}
}
});
}
}
答案 1 :(得分:2)
以下代码说明如何使用接近传感器:
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
// Do something with this sensor data.
}
@Override
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// Be sure to unregister the sensor when the activity pauses.
super.onPause();
mSensorManager.unregisterListener(this);
}}
尝试this链接以使用接近传感器,而Face靠近屏幕会关闭屏幕。
希望这有助于你。
答案 2 :(得分:2)
如果尝试Solkin发布的方法(使用唤醒锁),有很多设备的CPU使用率会很高。这是Android设备中的一个错误。
您应该使用onSensorChanged事件,只显示黑屏以避免任何问题。
答案 3 :(得分:0)
最好的方法是使用 DialogFragment,你显示一个黑屏并关闭它
@Override
public final void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
if(distance <10f)
showDialogFragment()
else
hideDialogFragment()
}