我正在尝试创建一个Android应用,该应用每24小时增加一次计数器。我只是在使用SharedPreferences,当它是时候它会增加共享首选项中的值。现在,我使用了FirebaseJobDispatcher,但是这样做的问题是,它的增量不一致。我通读了一些文档,我的理解是,在涉及一些网络调用的情况下,最好使用FirebaseJobDispatcher。我的问题是,我如何安排一个简单的作业在android中每24小时运行一次?请任何帮助和建议将非常有帮助。以下是我的FirebaseJobDispatcher代码。现在我只用2分钟来检查。
public class ScheduleIncrementJob {
private static final int UPDATE_INTERVAL_MINUTES = 2;
private static final int UPDATE_INTERVAL_SECONDS = (int)(TimeUnit.MINUTES.toSeconds(UPDATE_INTERVAL_MINUTES));
private static final int SYNC_FLEX_SECONDS = UPDATE_INTERVAL_SECONDS;
private static final String UPDATE_JOB_TAG = "update_counter_tag";
private static boolean sInitialized;
synchronized public static void scheduleUpdateCounter(final Context context){
if(sInitialized)return;
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
Job constraintUpdateJob = dispatcher.newJobBuilder()
.setService(IncrementJobService.class)
.setTag(UPDATE_JOB_TAG)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(UPDATE_INTERVAL_SECONDS,
UPDATE_INTERVAL_SECONDS + SYNC_FLEX_SECONDS))
.setReplaceCurrent(true)
.build();
dispatcher.schedule(constraintUpdateJob);
sInitialized = true;
}
}
答案 0 :(得分:0)
您可以使用AlarmManager类使用PendingIntent
计划重复的警报,该警报将在计划时完成。
https://developer.android.com/training/scheduling/alarms
被解雇后,我将为您提供DailyAlarm的样本:
public void setDailyAlarmOn(Context context, long alarmTime, Uri reminderTask, long repeatTime) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent operation =
yourJobHere.getReminderPendingIntent(context, reminderTask);
if (Build.VERSION.SDK_INT >= 23) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
} else {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
}
}
alarmTime-应该以毫秒为单位的第一次触发警报的时间
repeatTime-以毫秒为单位的时间-86400000 for 24h(1000 * 60 * 60 * 24)
Uri提醒任务-我创建的uri是为了不取消先前的警报,总之,这是警报应用程序的代码,它是数据库中行的uri。
操作-您需要创建的PendingIntent
我通过扩展IntentService并在onHandleIntent
中处理作业来做到这一点:
YourJobHere.class:
public class YourJobHere extends IntentService {
private static final String TAG = YourJobHere.class.getSimpleName();
public static PendingIntent getReminderPendingIntent(Context context, Uri uri) {
Intent action = new Intent(context, YourJobHere.class);
action.setData(uri);
return PendingIntent.getService(context, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
}
public YourJobHere() {
super(TAG);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//TODO: make your job here
}
}
如果需要,可以在GitLab上参考我的完整项目: https://gitlab.com/Domin_PL/SlothProfileScheduler
希望对您有帮助