Android: How to turn screen on and off programmatically?

后端 未结 16 2390
醉酒成梦
醉酒成梦 2020-11-22 13:05

Before marking this post as a \"duplicate\", I am writing this post because no other post holds the solution to the problem.

I am trying to turn off the device, then

16条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 13:41

    This is worked on Marshmallow

    private final String TAG = "OnOffScreen";
    private PowerManager _powerManager;
    private PowerManager.WakeLock _screenOffWakeLock;
    
    public void turnOnScreen() {
        if (_screenOffWakeLock != null) {
            _screenOffWakeLock.release();
        }
    }
    
    public void turnOffScreen() {
        try {
            _powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
            if (_powerManager != null) {
                _screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
                if (_screenOffWakeLock != null) {
                    _screenOffWakeLock.acquire();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

提交回复
热议问题