简体   繁体   中英

How to send local notification everyday at specific time in Android (API > 26)

I searched Stackoverflow and Google but no answers.

I can't find how to send notifications at specific time that occur everyday. Below API level of 26, it's not a problem. How can I do it in API>26?

I know that i need to create a channel to create notifications in API>26 but how to set it to repeat everyday?

From API 19 onwards, alarm delivery is inexact (the OS will shift alarms in order to minimize wakeups and battery use). These are new APIs which provide strict delivery guarantees:

  1. see setWindow(int, long, long, android.app.PendingIntent)
  2. setExact(int, long, android.app.PendingIntent)

So, we can use setExact:

public void setExact (int type, 
                long triggerAtMillis, 
                PendingIntent operation)

setExact can Schedule an alarm to be delivered precisely at the stated time.

This method is like set(int, long, android.app.PendingIntent), but does not permit the OS to adjust the delivery time. The alarm will be delivered as nearly as possible to the requested trigger time.

First, use setExact like this:

void scheduleAlarm(Context context) {
    AlarmManager alarmmanager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent yourIntent = new Intent();
    // configure your intent here
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, MyApplication.ALARM_REQUEST_CODE, yourIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmmanager.setExact(AlarmManager.RTC_WAKEUP, timeToWakeUp, alarmIntent);
}

Now, schedule the next occurrence (for making repeat) in the onReceive of your BroadcastReceiver like below:

public class AlarmReceiver extends BroadcastReceiver  {
  @Override
  public void onReceive(Context context, Intent intent) {
    // process alarm here
    scheduleAlarm(context);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM