Android: Keep camera-LED on after screen turns off

谁说我不能喝 提交于 2019-11-28 10:22:23

I have found a solution to the problem. When the phone turns off the screen it does deactivate the camera LED, but it allows a user to reactivate it like this:

@Override
public void onCreate() {
    // assume we start with screen on and save that state ;-)
    this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    screenOn = this.pm.isScreenOn();

    // program a timer which checks if the light needs to be re-activated
    this.mTimer = new Timer();
    this.mTimerTask = new TimerTask() {
        public void run() {
            // re-activate the LED if screen turned off
            if(!pm.isScreenOn() && pm.isScreenOn() != screenOn) {
                Log.i("SleepLEDservice", "re-activated the LED");

                // really it's NOT ENOUGH to just "turn it on", i double-checked this
                setFlashlight(Camera.Parameters.FLASH_MODE_OFF);
                setFlashlight(Camera.Parameters.FLASH_MODE_TORCH);
            }
            screenOn = pm.isScreenOn();                 
        }
    };
}

private void setFlashlight(String newMode) {
    try {
        this.frontCamPara = this.frontCam.getParameters();
        if(this.frontCamPara.getFlashMode() != newMode) {
            this.frontCamPara.setFlashMode(newMode);
            this.frontCam.setParameters(frontCamPara);  
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The key is changing the state back to FLASH_MODE_OFF and than back to FLASH_MODE_TORCH.

I don't know if HTC is in this camp, but several devices (notably the Moto Droid) cannot use the camera when the screen is off - they helpfully assume that you would never want to use your phone in this manner. If the screen locks, the app using the camera is put into the background and stops running.

The result is that the security cam/webcam apps I've seen have a feature to dim/black the screen, but they don't actually allow it to lock. This ensures that the camera continues to operate.

I suspect that because the LED is considered part of the camera hardware, it is facing the same limitations.

I did someething similar to stefanjunkers but was having problems getting it to work, the light sometimes came back on and stayed on, and sometimes it came back on then quickly turned off again. After a bit of fiddling I found that pausing the thread for a moment solved it:

setFlashlight(Camera.Parameters.FLASH_MODE_OFF);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
setFlashlight(Camera.Parameters.FLASH_MODE_TORCH);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!