在Android上安排JobService

时间:2017-10-02 00:13:51

标签: android scheduling jobservice

我有一份工作服务,我想要每三个小时一次,我已经完成了工作服务课程,但我不知道如何每三个小时执行一次。

这是我的Jobservice课程

public class CleanupJobService extends JobService {
private static final String TAG = CleanupJobService.class.getSimpleName();

@Override
public boolean onStartJob(JobParameters params) {
    Log.d(TAG, "Cleanup job started");
    new CleanupTask().execute(params);

    //Work is not yet complete
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    //No need to reschedule any jobs
    return false;
}

/* Handle access to the database on a background thread */
private class CleanupTask extends AsyncTask<JobParameters, Void, JobParameters> {

    @Override
    protected JobParameters doInBackground(JobParameters... params) {
        String where = String.format("%s = ?", DatabaseContract.TaskColumns.IS_COMPLETE);
        String[] args = {"1"};

        int count = getContentResolver().delete(DatabaseContract.CONTENT_URI, where, args);
        Log.d(TAG, "Cleaned up " + count + " completed tasks");

        return params[0];
    }

    @Override
    protected void onPostExecute(JobParameters jobParameters) {
        //Notify that the work is now done
        jobFinished(jobParameters, false);
    }
}

}

并在Manifest上注册

    <service
        android:name=".data.CleanupJobService"
        android:permission="android.permission.BIND_JOB_SERVICE"
        android:exported="true"/>

有什么想法解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

解决了,我使用jobInfo类来解决这个问题,代码看起来应该是这样的

ComponentName jobService = new ComponentName(getContext(), CleanupJobService.class); JobInfo task = new JobInfo.Builder(CLEANUP_JOB_ID, jobService) .setPeriodic(jobInterval) .setPersisted(true) .build();

jobInterval是我们希望服务执行的预定义时间,类型为Long并且具有millis格式。