如果应用程序在启动时运行,如何使屏幕不入睡?

How to make a screen not fall asleep if the app runs on boot?

我有必须在设备启动时启动的应用程序。它运行良好,但问题是当应用程序完成启动时,屏幕已经变暗了。怎样才能让它不睡着呢? 我的收件人:

<receiver
      android:enabled="true"
      android:exported="true"
      android:name=".view.receivers.BootReceiver"
      android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />

        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>


public class BootReceiver extends BroadcastReceiver {

  private final static String LOG_TAG = BootReceiver.class.getSimpleName();

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
      Log.i(LOG_TAG, "Loading after booting...");
      Intent startCalendarActivityIntent = new Intent(context, CalendarActivity.class);
      startCalendarActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(startCalendarActivityIntent);
    } else {
      Log.e(LOG_TAG, "Error while restarting after boot.");
    }
  }
}

在此设备上是 Android 6.0 .

您可以使用wakelocks, which need certain permissions, or you can put a flag in your onCreate method, which according to the docs不需要权限。

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

唤醒锁文档给出了上面的例子。