想要安排一个通知,该通知将在每周一的上午 11 点触发。 我为此使用 firebase 作业调度程序。 这是我实现的代码片段,但这不起作用。
Calendar currentDate = Calendar.getInstance();
while (currentDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
currentDate.add(Calendar.DATE, 1);
}
currentDate.set(Calendar.HOUR_OF_DAY, 11);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(SplashScreen.this));
Job myJob = dispatcher.newJobBuilder()
.setService(ScheduledNotificationService.class)
.setTag(dispatcherTag)
.setRecurring(true)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(Math.round(currentDate.getTime().getTime() / 1000), Math.round(currentDate.getTime().getTime() / 1000) + 60))
.setReplaceCurrent(false)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.build();
dispatcher.mustSchedule(myJob);
ScheduledNotificationService.class扩展了jobservice,但onStartJob永远不会被调用。
这里可能出了什么问题?
除了使用 Firebase 作业调度程序之外,还有更好/正确的方法吗?
FirebaseJobDispatcher并没有真正帮助,所以我使用了AlarmManager,它就像一个魅力。 这是我实现它的方式,
Calendar currentDate = Calendar.getInstance();
while (currentDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
currentDate.add(Calendar.DATE, 1);
}
currentDate.set(Calendar.HOUR_OF_DAY, hour);
currentDate.set(Calendar.MINUTE, minute);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
Intent intent = new Intent(mContext, AlarmReceiver.class);
intent.putExtra("extra info", "if needed");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, RequestCode, intent, 0);
AlarmManager am = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, currentDate.getTimeInMillis(), am.INTERVAL_DAY * 7, pendingIntent);
用于执行任何操作的 AlarmReceiver 类
public class AlarmReceiver extends BroadcastReceiver {
private Context mContext;
@Override
public void onReceive(Context context, Intent data) {
mContext = context;
//YOUR STUFF
}
}
此计划在用户重新启动设备后停止工作。重新启动完成后,不要忘记再次设置此设置。 为此,请在AndroidManifest中添加此内容并再次安排警报。
<receiver
android:name=".AlarmManager.AlarmBootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在 AlarmBootReceiver 类中再次安排警报。