android - 设备可以在前台服务之前休眠吗?

标签 android android-service wakelock

我知道以前我们需要使用 WakefulBroadcastReceiver 来确保在接收器 onReceive 和服务 onHandleIntent 之间设备不会再次进入休眠状态.

现在 Google 似乎已经弃用了 WakefulBroadcastReceiver,因为从接收器启动服务不再“正确”。

我正在做的一件事是从高优先级 FCM 通知启动前台服务。这在新的后台执行规则下是完全有效的。但由于 WakefulBroadcastReceiver 已被弃用,这是否意味着 startForegroundService 保证设备在 onReceiveonHandleIntent 之间保持足够长的唤醒时间?唤醒锁?或者我应该只在接收器中手动持有唤醒锁并将其发送到服务以释放?

最佳答案

Does that mean startForegroundService guarantees that device stays awake long enough between onReceive and onHandleIntent's wakelock?

没有。

Or should I just hold a wakelock manually in the receiver and send it to the service to release?

您可以在服务的 onCreate() 中请求部分唤醒锁,如下所示:

private PowerManager.WakeLock wakeLock;
@Override
public void onCreate() {
    super.onCreate();
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PARTIAL_WAKE_LOCK_TAG);
    ...
}

请记住在使用后或在 onDestroy() 中释放唤醒锁,如下所示:

@Override
public void onDestroy() {
    super.onDestroy();      
    if (wakeLock.isHeld()) {
        wakeLock.release();
    }
}

Google 建议避免使用唤醒锁,因为它会耗尽用户的电池电量。有多种 API 可用于各种用例。基于documentation ,您可以考虑以下备选方案:

  • If your app is performing long-running HTTP downloads, consider using DownloadManager.
  • If your app is synchronizing data from an external server, consider creating a sync adapter.
  • If your app needs to execute background tasks at regular intervals, consider using JobScheduler or Firebase JobDispatcher. For information on triggering tasks at specific intervals, see Intelligent Job-Scheduling.

关于android - 设备可以在前台服务之前休眠吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51868083/

相关文章:

android - 如何从 Intent 启动 ListActivity?

java - 在 Scala 中将 java 对象转换为 Object[]

java - Android 设备上的 PowerManager.WakeLock

java - 方法调用 ((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);可能会产生 NullPointerException

android - 在Android中实现故事功能

Android _ 从服务类重定向到另一个 Activity ?

Android IntentService 以空 Intent 触发

android - 如何在窗口管理器参数中添加 LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES?

android - WakeLock 已完成,但仍然存在错误,即使我正在释放它

android - 如何通过AlarmManager唤醒屏幕?