android:靠近脸部时关闭屏幕

时间:2010-06-10 21:35:23

标签: android screen

我的应用允许用户访问公司语音邮件。通常,当用户将设备握在耳边时,在通话时,屏幕会关闭,因此他们不会意外地按下按钮。当用户正在收听语音邮件时,我想让我的应用做同样的事情。

谁知道怎么做?

4 个答案:

答案 0 :(得分:25)

如果允许您查看开源代码而不会导致自己出现问题,请检查Android Phone Application的来源。具体为src/com/android/phone/PhoneApp.javasrc/com/android/phone/InCallScreen.java

来自src / com / android / phone / PhoneApp.java:

 //Around line 519
 // Wake lock used to control proximity sensor behavior.
 if ((pm.getSupportedWakeLockFlags()
          & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {
     mProximityWakeLock = pm.newWakeLock(
         PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
         LOG_TAG);
 }

 ....
// Around line 1334
if (((state == Phone.State.OFFHOOK) || mBeginningCall)&& !screenOnImmediately) {
  // Phone is in use!  Arrange for the screen to turn off
  // automatically when the sensor detects a close object.
  if (!mProximityWakeLock.isHeld()) {
      if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring...");
      mProximityWakeLock.acquire();
  } else {
      if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held.");
  }
} else {
  // Phone is either idle, or ringing.  We don't want any
  // special proximity sensor behavior in either case.
  if (mProximityWakeLock.isHeld()) {
    if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing...");
    // Wait until user has moved the phone away from his head if we are
    // releasing due to the phone call ending.
    // Qtherwise, turn screen on immediately
    int flags =
        (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE);
    mProximityWakeLock.release(flags);
  }
}

此外,如果您查看PowerManager类的代码,PROXIMITY_SCREEN_OFF_WAKE_LOCK已记录(但隐藏)并且应该按照您的要求执行(但我不确定这适用于哪个API级别) - 但不在表中出于某种原因。

/**
 * Wake lock that turns the screen off when the proximity sensor activates.
 * Since not all devices have proximity sensors, use
 * {@link #getSupportedWakeLockFlags() getSupportedWakeLockFlags()} to determine if
 * this wake lock mode is supported.
 *
 * {@hide}
 */
public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = WAKE_BIT_PROXIMITY_SCREEN_OFF;

如果您不害怕使用潜在的无证件功能,它应该完全符合您的需要。

答案 1 :(得分:5)

从API级别21(Lollipop)开始,您可以获得接近唤醒锁定:

if(powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
        wakeLock.setReferenceCounted(false);
        return wakeLock;
    } else {
        return null;
    }
}

然后你需要获得并释放锁。

PS:PowerManager#getSupportedWakeLockFlags被隐藏了,但现在已经存在了。他们发明了isWakeLockLevelSupported

答案 2 :(得分:2)

您所看到的是使用接近传感器。对于拥有一台设备的设备,您可以通过SensorManager访问它。

答案 3 :(得分:2)

可能你不再需要了它,但对于那些对代码感兴趣的人,你可以在http://code.google.com/p/speakerproximity/看看我的SpeakerProximity项目