我自己的应用程序使用与 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/