简体   繁体   English

安排android中的作业在特定时间运行

[英]Schedule a job in android to run at a specific time

I have an Android application which needs to send backup data every midnight to my cloud server. 我有一个Android应用程序需要每隔午夜将备份数据发送到我的云服务器。 For this I need to schedule the job to occur every 24 hours without fail. 为此,我需要安排每24小时一次的工作。 I have read about AlarmManager and JobScheduler class which can schedule your jobs effectively. 我已经阅读了有关AlarmManagerJobScheduler类的信息,可以有效地安排你的工作。

In my case I am using JobScheduler class and here is my scheduleJob() method which sets a job to schedule after every 86400000 milliseconds (ie. one day). 在我的情况下,我使用的是JobScheduler类,这里是我的scheduleJob()方法,它将作业设置为在每86400000毫秒(即一天)之后进行调度。

@RequiresApi(api =Build.VERSION_CODES.LOLLIPOP)
public void scheduleJob(View v){
    JobInfo.Builder builder = new JobInfo.Builder(1,new ComponentName(this,JobSchedule.class));
    builder.setPersisted(true);
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
    builder.setPeriodic(86400000);
    builder.setRequiresCharging(false);
    builder.setRequiresDeviceIdle(false);
    builder.setBackoffCriteria(10000,JobInfo.BACKOFF_POLICY_EXPONENTIAL);

    int test = jobScheduler.schedule(builder.build());
    if(test <= 0){
        //sth went wrong
    }

}

My question stands is, from where and how should I implement jobSchedule() so that I can get the script to run exactly at 12 midnight. 我的问题是,从哪里以及如何实现jobSchedule()以便我可以让脚本在午夜12点运行。

Also, if I call scheduleJob method from, say, Android's Activity XYZ 's onCreate() method, then everytime the Activity XYZ is called, it's override method onCreate() will be called and an additional job will be scheduled. 另外,如果我从Android的Activity XYZ的onCreate()方法调用scheduleJob方法,那么每次调用Activity XYZ时,都会调用它的覆盖方法onCreate()并调度另一个作业。 So what should I do and from where should I schedule the job such that only one job is scheduled for the entire lifetime of the application? 那么我应该做什么,从哪里安排工作,以便在应用程序的整个生命周期内只安排一项工作?

To summarize using an example, Whatsapp backs up its data every day at 2 am. 总结一个例子,Whatsapp每天凌晨2点备份数据。 Even if I have turned off my net connection, it backs up my data as soon as I come online. 即使我关闭了网络连接,它也会在我上线后立即备份我的数据。 I want to implement similar functionality in my application. 我想在我的应用程序中实现类似的功能。

You can use SharedPreference to implement one-time execution. 您可以使用SharedPreference实现一次性执行。 Something like this 像这样的东西

SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (isFirstRun)
{
    // Code to run once
    SharedPreferences.Editor editor = wmbPreference.edit();
    editor.putBoolean("FIRSTRUN", false);
    editor.commit();
}

根据文档JobInfo Builder ,setRequieresCharging和setRequieresDeviceIdle默认设置为false,因此您不需要将它们设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM