Android jobScheduler won't stop with jobFinished(params, false)

Daniel Braun picture Daniel Braun · May 27, 2016 · Viewed 12.6k times · Source

I'm tring to create a jobService. Here is what onStartJob() looks like.

@Override
public boolean onStartJob(JobParameters params) {
    Log.d(TAG, "onStartJob");
    Log.d(TAG, "Params= " + params.getJobId());
    param = params;
    jobFinished(params, false);
    //startAsync();
    return true;
}


@Override
public boolean onStopJob(JobParameters params) {
     Log.d(TAG, "onStopJob");
    return false;
}

Here is the code that is supposed to start the job.

public void startJobScheduler(){
    Log.d(TAG, "inside startJobScheduler");
    Activity activity = this.cordova.getActivity();
    Context context = activity.getApplicationContext();


     mJobScheduler = (JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE );
     JobInfo.Builder job = new JobInfo.Builder(111, new ComponentName(context, JobSchedulerService.class));

     job.setPeriodic(60000);
     Log.d(TAG, "before mJobScheduler.schedule(job.build())");
     if( mJobScheduler.schedule( job.build() ) <= 0 ) {
         Log.d(TAG, "job schedule failed");
     }
    Log.d(TAG, "333");
}

I can not get it to stop. It just keeps firing every 1-5 mins. I put jobFinished(params, false) in onStartJob() and commented out the task to try to kill it off right after it starts, but it just keeps firing. It seems jobFinished() fires something, as onDestroy() is called and my service gets destroyed, but then another job comes in with the same ID and starts it all back up.

I have BIND_JOB_SERVICE in the manifest like every example shows.

Any ideas on why jobFinished(params, false) doesn't seem to kill the setPeriodic(60000)?

Answer

Tom picture Tom · Jun 29, 2016

You have specified that a job is run periodically (every 60 seconds), so every 60~ seconds a new job is created and executed. jobFinished() is specific to a job, and simply indicates that it is done executing. You haven't cancelled anything.

Your (currently) accepted answer works for cancelling your scheduled job, but if all you want is a job that executes within 60 seconds and then stops, you should ommit setPeriodic() and use setOverrideDeadline(60000) instead. The job will run within 60 seconds and no more will be scheduled after it.