Skip to content

Instantly share code, notes, and snippets.

@wajahatkarim3
Created March 30, 2017 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wajahatkarim3/ee6b0bc1bfe0f6851304b29659413bb0 to your computer and use it in GitHub Desktop.
Save wajahatkarim3/ee6b0bc1bfe0f6851304b29659413bb0 to your computer and use it in GitHub Desktop.
Sample Android Job Scheduling
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