Reputation: 2097
In my Android app I need to run a background service every time the device is plugged in and idle (it should start after the user connects his device to the charger and end when he disconnects it).
What I want is a similar thing to listening for the ACTION_POWER_CONNECTED broadcast, but targeting Oreo this broadcast doesn't get sent.
I tried Android-Job from Evernote because it doesn't require Google Play Services, as Firebase JobDispatcher does.
new JobRequest.Builder(DemoSyncJob.TAG)
.setRequiresCharging(true)
.setRequiresDeviceIdle(true)
.build()
.schedule();
The problem is that I don't want to have to schedule the job every time. Instead, I want to schedule the job once and have it run every time the user connects his device to the charger.
How can it be done? Thank you.
Upvotes: 0
Views: 937
Reputation: 2097
Because it's fine for me to run the job only once a day, but only when the device is plugged in, I have solved the problem like this:
public class ProcessPhotosJob extends Job {
public static final String TAG = "process_photos_job";
@NonNull
@Override
protected Result onRunJob(Params params) {
new ProcessPhotos().execute(getContext());
scheduleForTomorrow();
return Result.SUCCESS;
}
public static void scheduleNow() {
schedule(1);
}
public static void scheduleForTomorrow() {
schedule(TimeUnit.DAYS.toMillis(1));
}
private static void schedule(long delayMillis) {
if (!JobManager.instance().getAllJobRequestsForTag(TAG).isEmpty()) {
// Job already scheduled
return;
}
new JobRequest.Builder(ProcessPhotosJob.TAG)
.setExecutionWindow(delayMillis, delayMillis + TimeUnit.DAYS.toMillis(1))
.setRequiresCharging(true)
.setRequiresDeviceIdle(true)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.build()
.schedule();
}
}
Hope it helps someone.
Upvotes: 1