Send local notifications in Android O

Viewed 2588

I cannot believe I'm asking this, but I want to schedule notifications in my Android app (repeating or not).

I managed to do this easily following the Android training article, using WakefulBroadcastReceiver and Services. But now, since I have to target the last Android APIs for my future updates, I have to make some changes to my code.

I believe that WakefulBroadcastReceiver has been deprecated, so I'm using a simple BroadcastReceiver instead.

Current implementation

Whenever I want to schedule an alarm, I'm sending an Intent to my BroadcastReceiver, and in the onReceive method, instead of the old call to startWakefulService(context, service);, I did a context.startService(service);. But with the background limitations, I cannot start a service when my app is in the background...

I have an error: java.lang.IllegalStateException: Not allowed to start service: app is in background

How can I change my code effectively to handle this problem? The service I call is the one that sends the notifications to the user.

Code

  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
    

EDIT

I cannot use JobScheduler as it will not guarantee me that the notifications will be sent in time.

I cannot start a foreground service too to send my notifications.

1 Answers

I've found an useful article, you can find out more by visiting this website

To simplify:

@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);
    }

The above code will schedule an alarm after 30 seconds and it will broadcast the notificationIntent.

Related