Venkatesh T
Venkatesh T

Reputation: 13

Which one best method for call a specific function at specific time , Job scheduler or alarm manager

I am communicating Bluetooth device with hardware. I want to send the data at a particular time into Bluetooth module which is the best method to schedule the call function, Which one I should use alarm manager or job scheduler.

Upvotes: 1

Views: 174

Answers (2)

Dhaval Solanki
Dhaval Solanki

Reputation: 4705

Its depend on your task if you want to perform the task when the app is killed also the device in DOZE mode then please use alarm manager with job scheduler otherwise you can use job scheduler.

Here is the proper method to schedule alarm.

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);
        }
    }

For the job scheduler user please use FirebaseJob dispatcher for lower version support

Upvotes: 0

Sagar
Sagar

Reputation: 24947

You should AlarmManager. You won't have that control with Jobscheduler. Scheduled jobs in JobScheduler will be executed based on criteria defined by OS which you cannot influence. If your use-case demands execution at particular time then AlarmManager should be your choice.

Based on the documentation:

Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.

  • If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
  • Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

Upvotes: 2

Related Questions