我搜索了 Stackoverflow 和 Google,但没有找到答案。
我找不到如何在每天发生的特定时间发送通知。 API级别低于26,这不是问题。我怎样才能在 API>26 中做到这一点?
我知道我需要创建一个 channel 来在 API>26 中创建通知,但如何将其设置为每天重复?
最佳答案
从 API 19 开始,警报传递不准确(操作系统将转移警报以最大程度地减少唤醒和电池使用)。这些新 API 提供严格的交付保证:
参见 setWindow(int, long, long, android.app.PendingIntent)
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/