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

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

我搜索了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:

  1. public void setExact (int type,
  2. long triggerAtMillis,
  3. PendingIntent operation)

setexact可以安排在指定的时间准确发送警报。
此方法类似于set(int,long,android.app.pendingent),但不允许操作系统调整传递时间。警报将尽可能接近请求的触发时间。
首先,使用 setExact 这样地:

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

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

  1. public class AlarmReceiver extends BroadcastReceiver {
  2. @Override
  3. public void onReceive(Context context, Intent intent) {
  4. // process alarm here
  5. scheduleAlarm(context);
  6. }
  7. }
展开查看全部

相关问题