Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

android - 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 -

public class GetImageService extends JobService {

    private GetImageTask getImageTask;

    @Override
    public boolean onStartJob(final JobParameters params) {
        getImageTask = new GetImageTask() {
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                jobFinished(params, true);
            }
        };
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        if (getImageTask != null) {
            getImageTask.cancel(true);
        }
        return false;
    }


    private class GetImageTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            // todo: connect to remote servers and make a network call here
            return null;
        }
    }
}

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.

<service 
    android: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,
                new ComponentName(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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...