gpt4 book ai didi

android - 在 Android 中每周一安排通知

转载 作者:行者123 更新时间:2023-11-29 23:47:25 26 4
gpt4 key购买 nike

想要安排一个通知,该通知将在每周一的上午 11 点触发。为此,我正在使用 firebase 作业调度程序。这是我已经实现的代码 fragment ,但这不起作用。

    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 类中再次安排警报。

关于android - 在 Android 中每周一安排通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51196658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com