JobScheduler只执行一次

时间:2017-05-22 16:47:45

标签: android android-jobscheduler

我每次都需要执行服务(1分钟)。我的JobScheduler执行一次,不再执行。

有什么问题?

JobNewClientsService在Manifest上声明,我在MainActivity中调用此类。

public class JobNewClientsService extends JobService {
private final String JOB_NAME = "Job_Service";
private Context mContext;
private AsyncOrderNewCommand asyncOrderNewCommand;

@Override
public boolean onStartJob(final JobParameters params) {
    Log.d(JOB_NAME, "StartJob");
    mContext = this;
    getNewCarts(params);
    return true;
}

@Override
public boolean onStopJob(final JobParameters params) {
    if (asyncOrderNewCommand != null) {
        asyncOrderNewCommand.cancel(true);
    }
    Log.d(JOB_NAME, "JobStop");
    return false;
}

public void showNotification() {
    Log.d(JOB_NAME, "Notification");
}

public void getNewCarts(final JobParameters params){
    asyncOrderNewCommand = new AsyncOrderNewCommand(new AsyncTaskException.AsyncTaskExceptionListener() {
        @Override
        public void onSuccess(Object result) {
            final List<Cart> cartList = (List<Cart>) result;
            if(cartList!=null && cartList.size()>0){
                showNotification();
                Log.d(JOB_NAME, "JobFinished");
                jobFinished(params, false);
            }
        }

        @Override
        public void onError(ApplicationException exception) {
            Log.d(JOB_NAME, "JobFinished");
            jobFinished(params, false);
        }
    });
    final CartsOrderDirectionCommand cartsOrderDirectionCommand = new CartsOrderDirectionCommand(CartsOrderDirectionCommand.OrderDirection.ASC);
    asyncOrderNewCommand.execute(cartsOrderDirectionCommand);
}

}

实例化我的工作

        JobScheduler jobScheduler =
            (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Log.d("SDK_VERSION","> ANDROID N");
        return jobScheduler.schedule(new JobInfo.Builder(1, new ComponentName(getPackageName(), JobNewClientsService.class.getName()))
                .setMinimumLatency(time)
                .setOverrideDeadline((long)(time * 1.05))
                .setPersisted(true)
                .build());
    } else {
        Log.d("SDK_VERSION","< ANDROID N");
        return jobScheduler.schedule(new JobInfo.Builder(1, new ComponentName(getPackageName(), JobNewClientsService.class.getName()))
                .setPeriodic(time)
                .setOverrideDeadline((long)(time * 1.05))
                .setPersisted(true)
                .build());
    }

1 个答案:

答案 0 :(得分:0)

我知道自发布以来已经有一段时间了,但是万一其他人遇到了这个问题: 调用 jobFinished 方法时,您需要发送true,因为您需要指定要在完成作业后重新计划作业。