Shakib Uz-Zaman
Shakib Uz-Zaman

Reputation: 621

How to set Alarm on android Oreo or Above?

I have implemented AlarmManager with background service, It works fine on devices below Oreo. But doesn't work on Android Oreo and above as Google stopped background services from working on Oreo and Above.

Is there any source code or any kind of resource which will help me to set alarms on Android Oreo or above devices?

After searching for a while I found out about JobsIntentService, but couldn't find enough information about it. And I don't know if it is the way to go. Basically, I want to show notifications on particular dates and times.

Thanks in Advance.

Upvotes: 0

Views: 3821

Answers (1)

Dhaval Solanki
Dhaval Solanki

Reputation: 4705

Please try bellow method it will work for you.

/**
 * Method for start Alarm on defined minute
 *  @param minutes Minute when you want to start after current time
 * @param context
 */
public static void startAlarm(Context context, int minutes) {
    Logger.print("AlarmReceiver startAlarm  called");
    Intent alarmIntent = new Intent(context, WakefulBroadcastReceiverService.class);
    alarmIntent.setAction("testAPP");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 123451, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    manager.cancel(pendingIntent);
    long alarmPeriodicTime = System.currentTimeMillis() + Utils.getTimeInMilliSec(Constant.TimeType.MINUTE, minutes);
    if (Build.VERSION.SDK_INT >= 23) {
        manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
    } else if (Build.VERSION.SDK_INT >= 19) {
        manager.setExact(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
    } else {
        manager.set(AlarmManager.RTC_WAKEUP, alarmPeriodicTime, pendingIntent);
    }
}

Upvotes: 4

Related Questions