programing

Android : 프로그래밍 방식으로 화면을 켜고 끄는 방법은 무엇입니까?

nasanasas 2020. 8. 30. 08:43
반응형

Android : 프로그래밍 방식으로 화면을 켜고 끄는 방법은 무엇입니까?


이 게시물을 "중복"으로 표시하기 전에 다른 게시물이 문제에 대한 해결책을 갖고 있지 않기 때문에이 게시물을 작성하고 있습니다.

장치를 끄려고하는데 몇 분이나 센서가 교체 된 후 다시 켜십시오.

디스플레이 테스트 끄기

다음을 사용하여 화면을 끌 수 있습니다.

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);

wl.release () 메서드를 사용하여 화면을 끌 수 없습니다.

디스플레이 테스트 켜기

내 첫 번째 추측은 다음과 같이 작동하지 않습니다. 아무 일도 일어나지 않고 화면이 꺼져 있습니다.

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = -1f;
getWindow().setAttributes(params);

그런 다음 깨어나 기 위해 시도했지만 성공하지 못했습니다.

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "tag");
wl.acquire();

마지막으로 결과없이 다음을 시도했습니다.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

대체로 이러한 방법에 대해 콘솔에 오류가 발생하지 않습니다. 전원 버튼을 사용하여 장치를 켰을 때 "화면이 켜져 있어야합니다"라는 테스트 텍스트가 화면에 표시됩니다. 이것은 코드가 실행되어야 함을 보여줍니다. 코드를 테스트 한 경우에만 대답하십시오.와 같은 많은 기능 params.screenBrightness = -1이 sdk에 따라 작동하지 않는 것 같습니다.


응용 프로그램이 포 그라운드에있는 동안에 만 이것이 적용되기를 원한다고 가정하겠습니다.

이 코드 :

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);

전통적인 의미에서 화면을 끄지 않습니다. 화면을 최대한 어둡게 만듭니다. 표준 플랫폼에서는 어둡게 할 수있는 한계가 있습니다. 기기에서 실제로 화면이 완전히 꺼지는 것을 허용하는 경우, 이는 해당 기기 구현의 일부 특이성이며 여러 기기에서 신뢰할 수있는 동작이 아닙니다.

사실이 기능을 FLAG_KEEP_SCREEN_ON과 함께 사용하면 특정 장치가 화면 밝기를 최대로 설정하도록 허용하더라도 화면이 꺼지지 않도록 (따라서 장치가 저전력 모드로 전환되는 것을) 허용하지 않습니다. 이것을 매우 명심하십시오. 화면이 실제로 꺼져있을 때보 다 훨씬 더 많은 전력을 사용하게됩니다.

이제 화면을 일반 밝기로 되돌리려면 밝기 값을 설정하기 만하면됩니다.

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);

이것이 이전에 설정 한 0 값을 대체하지 않는 이유를 설명 할 수 없습니다. 테스트로 특정 밝기로 강제하기 위해 강제 전체 밝기를 적용 할 수 있습니다.

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);

이것은 확실히 작동합니다. 예를 들어 Google의 도서 앱에서는이를 사용하여 책을 사용하는 동안 화면 밝기를 어둡게 설정 한 다음 끄면 일반 밝기로 돌아갈 수 있습니다.

디버그를 돕기 위해 "adb shell dumpsys window"를 사용하여 창의 현재 상태를 볼 수 있습니다. 창에 대한 데이터에서 현재 설정된 LayoutParams를 알려줍니다. 당신이 생각하는 가치가 실제로 거기에 있는지 확인하십시오.

다시 말하지만 FLAG_KEEP_SCREEN_ON은 별도의 개념입니다. 그것과 밝기는 서로 직접적인 영향을 미치지 않습니다. (그리고 밝기를 0으로 설정할 때 이미 설정 한 경우 밝기를 취소 할 때 플래그를 다시 설정할 이유가 없습니다. 플래그는 변경할 때까지 설정된 상태로 유지됩니다.)


화면 잠금 후 화면을 켜는 방법을 작성했습니다. 그것은 나를 위해 완벽하게 작동합니다. 시도 해봐-

    private void unlockScreen() {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

그리고이 메서드를 onResume().


나는 이것을 제안 할 것이다 :

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();

ACQUIRE_CAUSES_WAKEUP 플래그는 다음과 같이 설명됩니다.

일반 wake lock은 실제로 조명을 켜지 않습니다. 대신 조명이 켜지면 (예 : 사용자 활동에서) 계속 켜져 있습니다. 이 플래그는 WakeLock을 획득 할 때 화면 및 / 또는 키보드가 즉시 켜지도록 강제합니다. 일반적으로 사용자가 즉시 볼 수있는 중요한 알림에 사용됩니다.

또한 AndroidManifewst.xml 파일에 다음 권한이 있는지 확인하십시오.

<uses-permission android:name="android.permission.WAKE_LOCK" />

안녕하세요, 이것이 도움이되기를 바랍니다.

 private PowerManager mPowerManager;
 private PowerManager.WakeLock mWakeLock;

 public void turnOnScreen(){
     // turn on screen
     Log.v("ProximityActivity", "ON!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
     mWakeLock.acquire();
}

 @TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
 public void turnOffScreen(){
     // turn off screen
     Log.v("ProximityActivity", "OFF!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
     mWakeLock.acquire();
}

     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    screenLock.acquire();

  //later
  screenLock.release();

// 사용자 매니페스트 파일


Manifest 파일에서 적절한 권한을 요청 했습니까?

<uses-permission android:name="android.permission.WAKE_LOCK" />

AlarmManager 1 클래스를 사용 하여 활동을 시작하고 wake lock을 획득하는 인 텐트를 실행할 수 있습니다 . 그러면 화면이 켜지고 계속 켜져 있습니다. wakelock을 해제하면 장치가 자체적으로 절전 모드로 전환됩니다.

You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)


Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).

WindowManager.LayoutParams params = this.getWindow().getAttributes();

/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);

/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);

If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.


The best way to do it ( using rooted devices) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    .
    .
    .

    int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
    getWindow().addFlags(flags); // this is how your app will wake up the screen
    //you will call this activity later

   .
   .
   .
}

Now we have this two functions:

private void turnOffScreen(){

  try{
     Class c = Class.forName("android.os.PowerManager");
     PowerManager  mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
     for(Method m : c.getDeclaredMethods()){
        if(m.getName().equals("goToSleep")){
          m.setAccessible(true);
          if(m.getParameterTypes().length == 1){
            m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
          }
        }
     } 
  } catch (Exception e){
  }
}

And this:

public void turnOnScreen(){
  Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
  startActivity(i);
}

Sorry for my bad english.


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();
    }
}

To keep screen on:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Back to screen default mode: just clear the flag FLAG_KEEP_SCREEN_ON

getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission

before you use goToSleep(), you need use reflection just like:

public static void goToSleep(Context context) {
    PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    try {
        powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

Now,you can use goToSleep() to turn screen off.

This is what happens when the power key is pressed to turn off the screen.


I wouldn't have hope of "waking the screen" in the activity. If the screen is off the activity is probably in a paused state and shouldn't be running any code.

When waking up, there is the issue of the lockscreen. I don't know how any app can automatically bypass the lockscreen.

You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.

You could also attempt to start the activity direct from the service, but I really don't know if that will turn the screen on or bypass the lockscreen.


Regarding to Android documentation it can be achieve by using following code line:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

I have added this in my onCreate method and it works fine.

On the link you will find different ways to achieve this and general explanation as well.

Link to the documenation: https://developer.android.com/training/scheduling/wakelock.html


Simply add

    android:keepScreenOn="true" 

or call

    setKeepScreenOn(true) 

on parent view.


As per Android API 28 and above you need to do the following to turn on the screen

setShowWhenLocked(true); setTurnScreenOn(true); KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); keyguardManager.requestDismissKeyguard(this, null);

참고URL : https://stackoverflow.com/questions/9561320/android-how-to-turn-screen-on-and-off-programmatically

반응형