如何每天在特定时间在Android中发送本地通知(API> 26)

时间:2020-02-13 12:58:10

标签: java android notifications android-notifications

我搜索了Stackoverflow和Google,但没有找到答案。

我找不到如何在每天的特定时间发送通知。低于26的API级别,这不是问题。如何在API> 26中做到这一点?

我知道我需要创建一个通道来在API> 26中创建通知,但是如何将其设置为每天重复一次?

1 个答案:

答案 0 :(得分:0)

从API 19开始,警报传递是不精确的(操作系统将转移警报,以最大程度地减少唤醒和电池消耗)。这些是新API,可提供严格的交付保证:

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

因此,我们可以使用 setExact:

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

setExact可以安排在指定的时间准确发送警报。

此方法类似于set(int,long,android.app.PendingIntent),但不允许操作系统调整投放时间。该警报将尽可能接近要求的触发时间发送。

首先,像这样使用setExact

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

现在,安排下一次出现(重复)的时间 您的BroadcastReceiver的onReceive如下:

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