想安排一个通知,该通知将在每周的每个星期一的上午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作业调度程序外,还有其他更好/正确的方法吗?
答案 0 :(得分:1)
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类中再次安排警报。