Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule a job in android to run at a specific time

Tags:

android

I have an Android application which needs to send backup data every midnight to my cloud server. For this I need to schedule the job to occur every 24 hours without fail. I have read about AlarmManager and JobScheduler class which can schedule your jobs effectively.

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).

@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.

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. 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. 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.

like image 985
Shubham Shekhar Avatar asked Mar 05 '18 07:03

Shubham Shekhar


1 Answers

You can use SharedPreference to implement one-time execution. 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();
}
like image 116
MarGin Avatar answered Sep 20 '22 13:09

MarGin