Skip to content Skip to sidebar Skip to footer

Foregroundservice On Android Oreo Gets Killed

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

Solution 1:

You can use firebase job dispatcher for background service.

Code: Add this dependencies:

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'publicclassMyJobServiceextendsJobService
{
    privatestaticfinalStringTAG= MyJobService.class.getSimpleName();

    @OverridepublicbooleanonStartJob(JobParameters job)
    {
        Log.e(TAG, "onStartJob: my job service class is called.");
        // enter the task you want to perform.returnfalse;
    }

    @OverridepublicbooleanonStopJob(JobParameters job)
    {
        returnfalse;
    }
}

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
**/privatestatic 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.
**/privatevoid 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");
}

Post a Comment for "Foregroundservice On Android Oreo Gets Killed"