在Android O中如何发送本地通知

4
我简直不敢相信我会问这个问题,但我想在我的Android应用程序中安排通知(重复或不重复)。
我按照Android培训文章的说明轻松地做到了这一点,使用了WakefulBroadcastReceiverService。但是,因为我将来要针对最新的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 我该如何有效地改变我的代码以解决这个问题? 我调用的服务是向用户发送通知的服务。 代码
  1. 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);
    
  2. The Intent is received in the AlarmReceiver class

    // onReceive method
    context.startService(service); // The ERROR is raised here when my app is in bg
    

编辑

我不能使用JobScheduler,因为它不能保证通知及时发送。

我也不能启动前台服务来发送我的通知。


您可以使用“前台服务”、“JobIntentService”或“JobService”。 - egoldx
是的,@egoldx 是正确的。您可以使用任何提到的选项。我建议使用 JobScheduler,因为它似乎是这类任务最受推荐的选项。请查看链接以获取更多信息。https://developer.android.com/reference/android/app/job/JobScheduler - Mohit Ajwani
“JobScheduler” 不能保证通知及时发送,这对我来说非常关键。 - Youb
1
Work Manager 不适合发送通知。 - Youb
好的,一切都是相同的,但你必须调用ContextCompact.startForegroundService()而不是常规的startService,然后在你的服务中立即调用Service.startForeground()(前台服务需要在运行时显示通知)。如果你没有使用某些通知调用startForeground,你将会得到异常。 - egoldx
显示剩余3条评论
1个回答

0

我找到了一篇有用的文章,你可以通过访问这个网站来了解更多。

简而言之:

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
        notificationIntent.addCategory("android.intent.category.DEFAULT");

        PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 30);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
    }

以上代码将在30秒后安排一个闹钟,并广播notificationIntent

那么,答案就是在 onReceive 方法中发送通知? - Youb
1
我尝试了你的解决方案,但它不可靠:有时通知不会发送,因为广播接收器被杀死并且没有完成它的工作... - Youb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接