alarmmanager - Android O 和​​后台限制阻止简单的警报通知

标签 alarmmanager android-notifications wakeup android-8.0-oreo

我自己的应用程序使用与 2016 年 Google I/O 应用程序显示的完全相同的技术。see source

我需要在一个非常特定的时间点提醒用户 - 使用通知。

为此,我使用 AlarmManager在正确的时间点唤醒设备:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        am.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
    }
pendingIntent是这样创建的:
    final Intent intent = new Intent(MyAlarmService.ACTION_NOTIFY_RIDE, null, this, MyAlarmService.class);
    pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

现在,我的 MyAlarmService类是一个简单的IntentService处理唤醒只是为了为用户创建通知。

我在日志中收到的消息如下:
W/ActivityManager: Background start not allowed: service Intent { act=xxx.xxx.xxx.action.NOTIFY_RIDE flg=0x4 cmp=xxx.xxx.xxx./xxx.xxx.xxx.service.MyAlarmService (has extras) } 

现在,谷歌自己的实现显然已经坏了——即使我不想做任何繁重的后台工作,我也不能再使用这种技术了。但是我应该如何在一个非常特定的时间点唤醒用户呢? (把我的 App 想象成一个闹钟)

最佳答案

我的问题的答案很简单:

不要使用服务来显示通知(就像 Google 在其 IO Schedule 应用程序中所做的那样!),而是使用 BroadcastReceiver!

我不知道为什么 Google 确实使用了 IntentService,但现在在 Android O 上,由于后台执行限制,这根本不再起作用。

BroadcastReceiver 虽然显然仍然可以运行一小会儿并显示通知。

如果有人能告诉我为什么谷歌首先使用 IntentService ,我会加分……这让我花了很长时间才弄明白,因为我认为谷歌知道他们在做什么…… :(

关于alarmmanager - Android O 和​​后台限制阻止简单的警报通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016174/

相关文章:

android - 使用 Android 跟踪多个警报

android - 仅在手机上显示通知(不在 Android Wear 上)

android - 如何实现Notification的弃用方法

c - 如何唤醒暂停的线程?

java - 我是否应该显式唤醒一个占用 BlockingQueue.take() 的线程以提高性能?

android - 警报在创建后立即运行

android - 我应该如何使用 alarmmanager 每天和中午 12 点运行服务

java - 实例化重复警报后如何从 BroadcastReceiver 与 Activity 通信

java - 媒体样式 : RemoteServiceException: Bad notification posted from package

android - 收到通知时点亮屏幕android