简体   繁体   English

如何以编程方式在android中关闭屏幕

[英]how can I turn off screen in android programmatically

I want to turn off the screen.我想关掉屏幕。 So I tried to do it with PowerManager class but it didn't turn off screen.所以我试着用 PowerManager 类来做,但它没有关闭屏幕。

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

You can turn off screen by overriding system screen turn off time.您可以通过覆盖系统屏幕关闭时间来关闭屏幕。

First get system turn off time首先获取系统关闭时间

int defaultTurnOffTime =  Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 60000);

then put your turn off time然后把你的关机时间

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 1000);

and when the screen turned off, set default turn off time当屏幕关闭时,设置默认关闭时间

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, defaultTurnOffTime);

add below permission添加以下权限

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

It's not clear from the question if you've tried this, but you might need to make sure that you have the in your manifest:从问题中不清楚您是否尝试过此操作,但您可能需要确保清单中有 :

Any application using a WakeLock must request the android.permission.WAKE_LOCK permission in an element of the application's manifest.任何使用 WakeLock 的应用程序都必须在应用程序清单的元素中请求 android.permission.WAKE_LOCK 权限。

Another area that you might look is logcat to see if there is any stack traces or errors being logged, which could provide more context for people to help out.您可能会查看的另一个区域是 logcat,以查看是否记录了任何堆栈跟踪或错误,这可以为人们提供更多上下文以提供帮助。

@SuperDev , add the following to your Manifest: @SuperDev ,将以下内容添加到您的清单中:

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

This will resolve your app crash.这将解决您的应用程序崩溃问题。

Hope it helps :)希望能帮助到你 :)

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

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