我简直不敢相信我会问这个问题,但我想在我的Android应用程序中安排通知(重复或不重复)。
我按照Android培训文章的说明轻松地做到了这一点,使用了
我相信
我遇到了一个错误:java.lang.IllegalStateException: Not allowed to start service: app is in background 我该如何有效地改变我的代码以解决这个问题? 我调用的服务是向用户发送通知的服务。 代码
我按照Android培训文章的说明轻松地做到了这一点,使用了
WakefulBroadcastReceiver
和Service
。但是,因为我将来要针对最新的Android API进行更新,所以我必须对我的代码进行一些更改。我相信
WakefulBroadcastReceiver
已被弃用,所以我改用一个简单的BroadcastReceiver
。
当前实现
每当我想安排闹钟时,我就会发送一个Intent
给我的BroadcastReceiver
,然后在onReceive
方法中,我不再调用旧的startWakefulService(context, service);
,而是执行了一个context.startService(service);
。但由于后台限制,当我的应用程序在后台运行时,我无法启动服务......我遇到了一个错误:java.lang.IllegalStateException: Not allowed to start service: app is in background 我该如何有效地改变我的代码以解决这个问题? 我调用的服务是向用户发送通知的服务。 代码
Set the alarm
Intent broadcastIntent = new Intent(context, AlarmReceiver.class); // put the extras for the notification details // ... alarmIntent = PendingIntent.getBroadcast(context, idNotif, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, millis, interval, alarmIntent);
The
Intent
is received in theAlarmReceiver
class// onReceive method context.startService(service); // The ERROR is raised here when my app is in bg
编辑
我不能使用JobScheduler
,因为它不能保证通知及时发送。
我也不能启动前台服务来发送我的通知。
JobScheduler
,因为它似乎是这类任务最受推荐的选项。请查看链接以获取更多信息。https://developer.android.com/reference/android/app/job/JobScheduler - Mohit AjwaniContextCompact.startForegroundService()
而不是常规的startService
,然后在你的服务中立即调用Service.startForeground()
(前台服务需要在运行时显示通知)。如果你没有使用某些通知调用startForeground,你将会得到异常。 - egoldx