ForegroundService on android Oreo gets killed

前端 未结 1 928
梦谈多话
梦谈多话 2020-12-20 08:45

I\'m trying to build up a service which requests the device location every minute. I need this to work in background even when the application is closed. So far I managed to

相关标签:
1条回答
  • 2020-12-20 09:22

    You can use firebase job dispatcher for background service.

    Code: Add this dependencies:

    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    
    public class MyJobService extends JobService
    {
        private static final String TAG = MyJobService.class.getSimpleName();
    
        @Override
        public boolean onStartJob(JobParameters job)
        {
            Log.e(TAG, "onStartJob: my job service class is called.");
            // enter the task you want to perform.
            return false;
        }
    
        @Override
        public boolean onStopJob(JobParameters job)
        {
            return false;
        }
    }
    

    Create a job in the activity, you do it the way you used to do for background services.

    /**
     * 2018 September 27 - Thursday - 06:36 PM
     * create job method
     *
     * this method will create job
    **/
    private static Job createJob(FirebaseJobDispatcher dispatcher)
    {
        return dispatcher.newJobBuilder()
                //persist the task across boots
                .setLifetime(Lifetime.FOREVER)
                //.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
                //call this service when the criteria are met.
                .setService(MyJobService.class)
                //unique id of the task
                .setTag("TAGOFTHEJOB")
                //don't overwrite an existing job with the same tag
                .setReplaceCurrent(false)
                // We are mentioning that the job is periodic.
                .setRecurring(true)
                // Run every 30 min from now. You can modify it to your use.
                .setTrigger(Trigger.executionWindow(1800, 1800))
                // retry with exponential backoff
                .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
                //.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                //Run this job only when the network is available.
                .setConstraints(Constraint.ON_ANY_NETWORK)
                .build();
    }
    
    /**
     * 2018 September 27 - Thursday - 06:42 PM
     * cancel job method
     *
     * this method will cancel the job USE THIS WHEN YOU DON'T WANT TO USE THE SERVICE ANYMORE.
    **/
    private void cancelJob(Context context)
    {
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
        //Cancel all the jobs for this package
        dispatcher.cancelAll();
        // Cancel the job for this tag
        dispatcher.cancel("TAGOFTHEJOB");
    }
    
    0 讨论(0)
提交回复
热议问题