Created
March 30, 2017 13:10
-
-
Save wajahatkarim3/ee6b0bc1bfe0f6851304b29659413bb0 to your computer and use it in GitHub Desktop.
Sample Android Job Scheduling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int scheduleFirstAt(int aDay, int hours, int mins) { | |
int jobID = -1; | |
long startMs = 0L, endMs = 0L; | |
int MARGIN_TIME = 30; | |
// Current Day | |
DateTime currentDay = new DateTime(); | |
// Reminder Day | |
Calendar cal = Calendar.getInstance(); | |
cal.set(Calendar.HOUR_OF_DAY, hours); | |
cal.set(Calendar.MINUTE, mins); | |
DateTime reminderDay = new DateTime(cal); | |
// Monday = 1 -> Sunday = 7 | |
if (aDay >= currentDay.getDayOfWeek()) | |
{ | |
int diffInDays = aDay - currentDay.getDayOfWeek(); | |
reminderDay = reminderDay.plusDays(diffInDays); | |
startMs = reminderDay.getMillis() - System.currentTimeMillis(); | |
endMs = reminderDay.plusMinutes(MARGIN_TIME).getMillis() - System.currentTimeMillis(); | |
} | |
else | |
{ | |
int diffInDays = (7 - currentDay.getDayOfWeek()) + aDay; | |
reminderDay = reminderDay.plusDays(diffInDays); | |
startMs = reminderDay.getMillis() - System.currentTimeMillis(); | |
endMs = reminderDay.plusMinutes(MARGIN_TIME).getMillis() - System.currentTimeMillis(); | |
} | |
PersistableBundleCompat extras = new PersistableBundleCompat(); | |
extras.putInt("day", aDay); | |
extras.putInt("minutes", mins); | |
extras.putInt("hours", hours); | |
jobID = new JobRequest.Builder(ShowNotificationJob.TAG) | |
.setExecutionWindow(startMs, endMs) | |
//.setExact(startMs) | |
.setExtras(extras) | |
.setPersisted(true) | |
.build() | |
.schedule(); | |
return jobID; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment