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

标签 java android notifications android-notifications

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

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

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

最佳答案

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

  1. 参见 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 可以安排在指定时间准确发送警报。

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

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

关于java - 如何在Android中每天的特定时间发送本地通知(API > 26),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60208436/

相关文章:

Java重复捕手for循环仍然返回欺骗

java - 使用 GCM 发送推送消息时错误代码 "notRegistered"是什么意思?

ios - 如何在 iPhone 打开或将要关闭时通知您的应用程序?

ASP.NET MVC + SQL Server 应用程序 : Best Way to Send Out Event-Driven E-mail Notifications

android - 删除或隐藏 android 中的通知栏

java - 是否可以一起使用intellij idea和eclipse

java - 在 Java 中,哪个更快 - String.contains ("some text") 或查找相同文本的正则表达式?

android - 多次更改相对布局的高度

Android 即时应用程序和应用程序链接的使用

java - 为什么具体类的一个子类可以声明为抽象的,而父类的一些方法可以被重写并声明为抽象的?