ForegroundService on android Oreo gets killed

杀马特。学长 韩版系。学妹 提交于 2019-11-29 12:54:19

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");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!