Skip to content Skip to sidebar Skip to footer

How To Call Service In Background, When Application Is Close, That Time Continues Work Service And Call Api ?

I work on one api call in background service every 10 minute, this one worked same as when application is close, how it is possible?

Solution 1:

your question is not fully clear. I'm assuming that the following is your question and will try to answer it -

" How to run services that run in background and also continuously runs when the app is closed to connect to remote servers ? "

The best way to achieve this is by using the JobScheduler API. JobScheduler helps you to perform network operations efficiently by queueing your requests in batches thereby saving battery life. This helps you to give a better user experience.

To use the JobScheduler API you will have to create a JobService. JobService extends Service, enabling the system to run your job even if the app is in background. You will be required to implement the following methods :

onStartJob()
onStopJob()

For complicated tasks like network requests, return true in onStartJob() to let the system know that a background network thread is still running and hold on to the wake lock until the network thread has finished. The JobService runs on the main thread like any other service and you have to take care of running network operations in a separate thread like AsyncTask.

onStopJob() is called when the job conditions to run the job are not matched. Return true to tell the system to automatically run/reschedule the job when job conditions are met.

Below is an example code to help you better understand what's going on -

publicclassGetImageServiceextendsJobService {

    privateGetImageTask getImageTask;

    @OverridepublicbooleanonStartJob(final JobParameters params) {
        getImageTask = newGetImageTask() {
            @OverrideprotectedvoidonPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                jobFinished(params, true);
            }
        };
        returntrue;
    }

    @OverridepublicbooleanonStopJob(JobParameters params) {
        if (getImageTask != null) {
            getImageTask.cancel(true);
        }
        returnfalse;
    }


    privateclassGetImageTaskextendsAsyncTask<Void, Void, Void> {
        @OverrideprotectedVoiddoInBackground(Void... voids) {
            // todo: connect to remote servers and make a network call herereturnnull;
        }
    }
}

As JobService is a Service, you must declare it in the application manifest file. Add the BIND_JOB_SERVICE permission and set exported to true to let the system access your JobService.

<serviceandroid:name=".activity.GetImageService"android:permission="android.permission.BIND_JOB_SERVICE"android:exported="true"/>

JobScheduler shows it's real power with it's conditions that you set using the JobInfo object. JobScheduler works based on time and various conditions. This makes you not to write AlarmManager or Service and save the phone battery by not making unnecessary network calls. You can set conditions like network required which means your JobService will only run when there's network connection. Setting a condition as persisted will ensure your job to run even after the phone reboots.

JobScheduler jobScheduler = (JobScheduler)
                getSystemService(Context.JOB_SCHEDULER_SERVICE);

        jobScheduler.schedule(new JobInfo.Builder(1000,
                newComponentName(this, GetImageService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build());

Calling the schedule() method ensures your job gets scheduled by the system. This makes your job to run even when all the conditions are met in background without the user even opening the app. For example, you could use this to update your tables with the latest data from the servers even before the user asks for it. This will help you to provide a very good user experience by making the data available as soon as the user opens the app and not making him to wait for data.

With Android O releasing this year you should also consider reading about background limits. With Android O Google prefers developers use JobScheduler extensively.

Refer to this blog post by Google for more info - https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

Also an example app on GitHub by developers at Google - https://github.com/romannurik/muzei/tree/master/main/src/main/java/com/google/android/apps/muzei/sync

Solution 2:

Use Alarm manager api see below Scheduling Repeating Alarms https://developer.android.com/training/scheduling/alarms.html.

Post a Comment for "How To Call Service In Background, When Application Is Close, That Time Continues Work Service And Call Api ?"