what is the alternative of AlarmManager to schedule long duration time tasks in Oreo?

Viewed 628

I am creating an app that will set the android device in silent mode automatically every day at 8:00 am? I used AlarmManager , Job-Scheduler with foreground service but it will not work on android 8 or above .. I also use WorkManager but WorkManager requires certain constraints to run the job.. plZzz Help me

1 Answers

I recommend sticking with a Worker, it is a simpler parallel to WorkManager but without mandatory constraints. Worker and WorkManager automatically handle lower SDK versions by stepping-down to AlarmManager.

I've replaced my app's AlarmManager with Worker, it is much more stable for periodic tasks.

All you need is a Worker class MyPeriodicWorker.class:

public class MyPeriodicWork extends Worker {

    private static final String TAB = MyPeriodicWork.class.getSimpleName();

    public MyPeriodicWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }


    @NonNull
    @Override
    public Result doWork() {
        Log.e(TAB,"PeriodicWork in BackGround");
        // Run your task here

        return Result.success();
        }
    }

and a WorkRequest instance called from another class. In your case, you want a PeriodicWorkRequest for a recurring task. You must specify the parameter for flex if you want the task to run at the specified time (minimum flex of <5 minutes early):

    PeriodicWorkRequest mPeriodicWorkRequest = new PeriodicWorkRequest.Builder(MyPeriodicWorker.class,
            periodMS, TimeUnit.MILLISECONDS, periodFlex, TimeUnit.MINUTES)
            .addTag("PeriodicWorkRequest")
            .build();

The above is all you need to use it, then use WorkManager enqueue to start.

    WorkManager.getInstance(context).enqueue(mPeriodicWorkRequest);
Related