Created
November 28, 2018 08:35
-
-
Save hi-manshu/7ce6307ea41f37df53eaf6661f5a3360 to your computer and use it in GitHub Desktop.
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 class AlarmManagerTaskBroadCastReceiver extends BroadcastReceiver { | |
| public static final String CUSTOM_INTENT = "com.test.intent.action.ALARM"; | |
| public static final Context ctx = ApplicationInit.getAppContext(); | |
| @Override | |
| public void onReceive(Context context, Intent intent) { | |
| /* enqueue the job */ | |
| AlarmJobIntentService.Companion.enqueueWork(context, intent); | |
| } | |
| public static void cancelAlarm() { | |
| AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE); | |
| /* cancel any pending alarm */ | |
| assert alarm != null; | |
| alarm.cancel(getPendingIntent()); | |
| } | |
| public static void setAlarm(boolean force) { | |
| cancelAlarm(); | |
| Util.showDebugLog("setAlarmCtx","Alarm Started"); | |
| AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE); | |
| // EVERY 2 MINUTES | |
| long delay = (1000 * 60 * 2); | |
| long when = System.currentTimeMillis(); | |
| if (!force) { | |
| when += delay; | |
| } | |
| /* fire the broadcast */ | |
| int SDK_INT = Build.VERSION.SDK_INT; | |
| if (SDK_INT < Build.VERSION_CODES.KITKAT) { | |
| assert alarm != null; | |
| alarm.set(AlarmManager.RTC_WAKEUP, when, getPendingIntent()); | |
| } else if (SDK_INT < Build.VERSION_CODES.M) { | |
| assert alarm != null; | |
| alarm.setExact(AlarmManager.RTC_WAKEUP, when, getPendingIntent()); | |
| } else { | |
| assert alarm != null; | |
| alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, when, getPendingIntent()); | |
| } | |
| } | |
| private static PendingIntent getPendingIntent() { | |
| Intent alarmIntent = new Intent(ctx, AlarmManagerTaskBroadCastReceiver.class); | |
| alarmIntent.setAction(CUSTOM_INTENT); | |
| return PendingIntent.getBroadcast(ctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment