Friday, 12 October 2018

How to update running JobService with new request?

I have an app with the option to download files. For this purpose, I've implemented DownloadService which will firstly do the database query to get download candidates and then build queue for download. Once the queue is built, it will start processing downloads 1 by 1 until the queue is empty and then will finish itself. While service is running user can add more download requests (send ACTION to running service to re-build queue). But we can't use background service when targeting Oreo or newer version of Android anymore, and I would like to avoid implementing it as foreground service to avoid displaying notification while determining download queue and not doing actual file download.

I've tried to schedule it with setOverrideDeadline(0) using JobScheduler API but instead of updating running job, the old one was destroyed, and the new one created. I've also tried to enqueue JobWorkItem instead, but onStartJob of JobService (where I am supposed to dequeue work) is not called if the job is already running so I can't update it with new requests.

EDIT 1: I have an experimental implementation where I will check if my JobService is running using this sample code

private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
        if("com.example.MyJobService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

If job is not running I will schedule it, but if it is running I will send event to this job using EventBus and update job with new request. But I would prefer 'pure' JobScheduler's API solution.

EDIT 2: I have also option to download multiple files in parallel and to change priority of queued downloads.

Do anybody know how to keep posting new requests (actions) to running job without creating a new one with JobScheduler API? (without 3rd party libraries)



from How to update running JobService with new request?

No comments:

Post a Comment