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

azpvetkf  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(321)

我搜索了stackoverflow和google,但没有找到答案。
我找不到如何在每天发生的特定时间发送通知。低于api级别26,这不是问题。如何在api>26中执行?
我知道我需要创建一个通道来创建api>26中的通知,但是如何将其设置为每天重复?

aurhwmvo

aurhwmvo1#

从api 19开始,警报传递是不精确的(操作系统将改变警报以最小化唤醒和电池使用)。这些新API提供了严格的交付保证:
see setWindow(int, long, long, android.app.PendingIntent) setExact(int, long, android.app.PendingIntent) 所以,我们可以使用setexact:

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

setexact可以安排在指定的时间准确发送警报。
此方法类似于set(int,long,android.app.pendingent),但不允许操作系统调整传递时间。警报将尽可能接近请求的触发时间。
首先,使用 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);
}

现在,在 onReceive 您的广播接收器如下:

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

相关问题