简体   繁体   English

Android关闭屏幕

[英]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. 我使用了PowerManagerwl.release()方法,但它不起作用。 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 我在堆栈溢出时找到了答案: 在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. 如果您不使用权限,程序将在尝试锁定时因SecurityException而崩溃,因此这不是问题。 The correct method is: (obtains WakeLock on start, gives it up when the application loses focus (onPause) 正确的方法是:(在启动时获取WakeLock,在应用程序失去焦点时放弃它(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")) 这应该是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 强制屏幕

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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