关于 android 应用程序中的屏幕

About the screen on in android application

我有一个 Android 应用程序,我想保持屏幕打开。但有时我不想一直开着屏幕。我该怎么办?

编辑: 我已经使用此代码将我的屏幕设置为:

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

查看文档 -

android:keepScreenOn="true"

在布局中或以编程方式

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

https://developer.android.com/training/scheduling/wakelock.html

你的问题不清楚,但我想你正在寻找这个。你可以从语法上做到这一点。

Keep Screen Awake

或将其添加到您的布局中

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

找到 activity 的根布局。例如,如果根布局是 LinearLayout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xml);
    LinearLayout root = (LinearLayout) findViewById(R.id.root_container):

    // and according to your preference you can set 
    root.setKeepScreenOn(true/false);

官方文档说

 /**
 * Controls whether the screen should remain on, modifying the
 * value of {@link #KEEP_SCREEN_ON}.
 *
 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
 *
 * @see #getKeepScreenOn()

 */

更多参考请关注thislink

当您需要您的应用程序不保持屏幕打开时,您可以使用以下代码清除 FLAG_KEEP_SCREEN_ON 标志:

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

你应该使用这个:

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

然后:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

希望对您有所帮助。