Android JobScheduler 每天仅运行一次

13

我查看了可以在Android API 21及以上版本使用的JobScheduler API。我想安排一个需要互联网并且每天只运行一次,或者在成功执行后可选择每周运行一次的任务。我没有找到与这种情况相关的示例。有人可以帮助我吗?谢谢。


2
使用setPeriodic()来设置定时,使用setRequiredNetworkType()来设置网络要求。 - CommonsWare
请观看以下链接:https://gist.github.com/codinginflow/4c85bfb052cd7a92ef816ab1845c669a - Abanoub Hany
1个回答

20

请跟随一个简单的例子回答您的问题,我相信它会对您有所帮助:

AndroidManifest.xml:

<service android:name=".YourJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />

YourJobService.java:

class YourJobService extends JobService {
    private static final int JOB_ID = 1;
    private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L; // 1 Day
    private static final long ONE_WEEK_INTERVAL = 7 * 24 * 60 * 60 * 1000L; // 1 Week

    public static void schedule(Context context, long intervalMillis) {
        JobScheduler jobScheduler = (JobScheduler) 
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName =
            new ComponentName(context, YourJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setPeriodic(intervalMillis);
        jobScheduler.schedule(builder.build());
    }

    public static void cancel(Context context) {
        JobScheduler jobScheduler = (JobScheduler)
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.cancel(JOB_ID);    
    }

    @Override
    public boolean onStartJob(final JobParameters params) {
        /* executing a task synchronously */
        if (/* condition for finishing it */) {
            // To finish a periodic JobService, 
            // you must cancel it, so it will not be scheduled more.
            YourJobService.cancel(this);
        }

        // false when it is synchronous.
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }
}

在安排任务后,调用YourJobService.schedule(context, ONE_DAY_INTERVAL)。只有在连接到某些网络并且一天内(即每天)连接到网络时才会调用它。

注意: 周期性作业只能通过调用JobScheduler.cancel(Job_Id)来完成,而 jobFinished()方法不能完成它。

注意: 如果您希望将其更改为“每周一次” - YourJobService.schedule(context, ONE_WEEK_INTERVAL)

注意:Android L上的周期性作业可以在您设置的任何时间运行一次。


在哪里调用schedule()函数?我在oncreate()中调用了它,但每次打开应用程序时通知都会显示出来,而周期性的任务也没有工作。 - Prajwal Waingankar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接