唤醒锁已移除,但应用处于活动状态时屏幕仍未关闭

Wake lock removed but screen still not turning off when app is active

我在我的应用程序中获得了 WAKE_LOCK 权限,但后来我删除了该权限。但是当我的应用程序处于活动状态时,phone 仍然没有关闭屏幕。是否有任何其他设置可以阻止 phone 关闭?

根据 the docs 的说法,'settings' 可以防止屏幕进入睡眠状态:

Certain apps need to keep the screen turned on, such as games or movie apps. The best way to do this is to use the FLAG_KEEP_SCREEN_ON in your activity (and only in an activity, never in a service or other app component). For example:

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  }

The advantage of this approach is that unlike wake locks (discussed in Keep the CPU On), it doesn't require special permission, and the platform correctly manages the user moving between applications, without your app needing to worry about releasing unused resources.

Another way to implement this is in your application's layout XML file, by using the android:keepScreenOn attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Using android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON. You can use whichever approach is best for your app. The advantage of setting the flag programmatically in your activity is that it gives you the option of programmatically clearing the flag later and thereby allowing the screen to turn off.

Note: You don't need to clear the FLAG_KEEP_SCREEN_ON flag unless you no longer want the screen to stay on in your running application (for example, if you want the screen to time out after a certain period of inactivity). The window manager takes care of ensuring that the right things happen when the app goes into the background or returns to the foreground. But if you want to explicitly clear the flag and thereby allow the screen to turn off again, use clearFlags():

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).

Wakelock 是另一个,但既然你已经知道了,我认为我不需要在这里提及它。

为避免耗尽电池电量,闲置的 Android 设备会很快进入睡眠状态。但是,有时应用程序需要唤醒屏幕或 CPU 并使其保持清醒状态以完成某些工作。

使用:

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

这种方法比唤醒锁更有效,而且不需要任何权限

并清除标志:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).