3

In my Android app I need to do some work every time the user plugs their device. For this purpose right now I use a BroadcastReceiver, which starts my IntentService to do the work when the user plugs the device and stops it when the device becomes unplugged.

Right now I'm thinking of using JobScheduler for Android 5.0+, but what I'm seeing is that with JobScheduler, I would have to schedule my job within the app, by calling

JobScheduler.schedule(JobInfo);

But this is a problem to me, because I want my job to run every time the user connects their device to the charger, even without the user having to open my app.

For this reason, I think one way would be to schedule it the first time the user opens the app, and then always force reschedule, since I cannot trust on the user opening my app every day (which, due to the nature of my app, certainly won't happen).

So, should I stick with BroadcastReceiver or use JobScheduler for Android 5.0+?

And in the case of using JobScheduler, should I schedule my job only once and then always return true in order to force rescheduling?

Thank you.

Ernestina Juan
  • 957
  • 1
  • 9
  • 24
  • Listen to battery change state via a BroadcastReceiver : http://stackoverflow.com/questions/11277302/i-cant-receive-broadcast-on-battery-state-change – Goufalite Jun 02 '16 at 12:17

2 Answers2

1

So, should I stick with BroadcastReceiver or use JobScheduler for Android 5.0+?

Use JobScheduler, this can improve your app’s performance, along with aspects of system health such as battery life. Also, JobScheduler persists through device reboots and supports batch scheduling by which the android system can combine pending jobs thus reducing battery usage. Moreover, you can do distinguish between android versions thus using JobScheduler on Lollipop and up, and AlarmManager on older versions.

And in the case of using JobScheduler, should I schedule my job only once and then always return true in order to force rescheduling?

Now, there are 2 ways to do this :

  1. As you guessed, scheduling your job only once and always returning true in jobFinished() - this should do the trick.

  2. Upon completing a job (originally scheduled by you by calling JobScheduler.schedule(JobInfo)), you schedule another job by calling the same. This will schedule consequent jobs once each job is about to be completed.

Shrey Garg
  • 1,317
  • 1
  • 7
  • 17
-2

Jobscheduler runs in the background and persists through reboots so you should be fine.

Oliver84
  • 307
  • 2
  • 14