[英]How to send local notification everyday at specific time in Android (API > 26)
我搜索了 Stackoverflow 和 Google 但沒有答案。
我找不到如何在每天發生的特定時間發送通知。 API 級別低於 26,這不是問題。 我怎樣才能在 API>26 中做到這一點?
我知道我需要創建一個頻道來在 API>26 中創建通知,但如何將其設置為每天重復?
從 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.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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.