简体   繁体   中英

Android Turn screen Off

I can't turn off the screen using this code. I used PowerManager and wl.release() method, but it doesn't work. Can somebody show me an example?

  PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
   wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen"); 

This is part of my function:

  stateString = "nextone";
  if(stateString=="nextone"){        
  wl.release();
   }

I also added permission in the manifest but no result.

I found the answer over here on stack overflow: Turn off screen on Android

Copied from there:

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

I tried this out and it seems to work.

您可以使用

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try 
{
    Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000*15);
} 
catch (NumberFormatException e) 
{
    Log.e("aa", "could not persist screen timeout setting", e);
}

How to detect switching between user and device

If you don't use a permission, the program will crash with a SecurityException when it tries to lock, so that isn't the problem. The correct method is: (obtains WakeLock on start, gives it up when the application loses focus (onPause)

//declared globally so both functions can access this
public PowerManager.WakeLock wl;

///////////onCreate
//stop phone from sleeping
PowerManager powman = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = powman.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "NameOfLock");
wl.acquire();

///////////onPause
wl.release();

//////////for completion's sake, onResume
if(!wl.isHeld()){
    wl.acquire();
}

However, your problem is actually in this check

if(stateString=="nextone")

This should be if(stateString.equals("nextone"))

please check this link before proceeding with wake lock. if it does not solve your problem then you can proceed with wake lock.

Force Screen On

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM