Google has already developed an advanced version of Alarm Manager which has much more modern functionality and works in a battery-efficient manner.
Since Android Oreo and above, Google has introduced doze mode which suspends almost all the Alarm Manager requests. This keeps the alarms from ringing until the mobile wakes up from doze mode. Many developers have complained a lot about this functionality been jeoparding the normal behavior of their apps. Some have found workarounds, while some have limited the background work in their application but most of the developers don't know that Google has already developed an advanced version of Alarm Manager which has much more modern functionality and works in a battery-efficient manner.
Credits: https://developer.android.com/ |
What is Work Manager?
Types of Work:
How to use Work Manager:
[Java Version
implementation "androidx.work:work-runtime:2.4.0"
Kotlin Version
implementation "androidx.work:work-runtime-ktx:2.4.0"]
To create a periodic work request, add the following lines:
[WorkRequest uploadWorkRequest = new PeriodicWorkRequest.Builder(NotificationWorker.class, 1, TimeUnit.DAYS).build();
WorkManager.getInstance(c).enqueue(uploadWorkRequest);]
Now write the background task, you want to perform here:
[public class NotificationWorker extends Worker {
private static Context context;
public NotificationWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
this.context = context;
}
@Override
public Result doWork() {
try {
//TODO YOUR PREFERRED BACKGROUND TASK
return Result.success();
} catch (Exception e) {
e.printStackTrace();
return Result.failure();
}
}
}]
Thats it. You have successfully implemented periodic work requests using the Work Manager.
To schedule periodic Work Manager tasks with Alarm Manager, instead of your usual Alarm Manager code, write this code :
[alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeinmillis,notifyPendingIntent);]
This line will wake Alarm Manager even when it is in doze mode and will work without any problems in Android Oreo and above versions.
COMMENTS