Search code examples
androidpostserveraccelerometer

Sending data weekly to the server using POST


I am working on an accelerometer application. My application is saving data on local storage i.e. user's smartphone. I want to send it to the server, but I want to send it weekly. Is there any function that can be used to send the data automatically after a week.

I am using Android Studio for this. Sorry, I am new to this, please help.

Thanks.


Solution

  • You use WorkManager architecture component to achieve it. Schedule a PeriodicWorkRequest as follows:

    Create Worker class:

    public class MyWorker extends Worker {
        @Override
        public Worker.WorkerResult doWork() {
    
            // Send your data to server
    
            // Indicate success or failure with your return value:
            return WorkerResult.SUCCESS;
    
            // (Returning RETRY tells WorkManager to try this task again
            // later; FAILURE says not to try again.)
        }
    }
    

    Schedule the Work:

      PeriodicWorkRequest periodicWork = new 
      PeriodicWorkRequest.Builder(MyWorker.class, 7, TimeUnit.DAYS)
                                       .build();
      WorkManager.getInstance().enqueue(periodicWork);
    

    This creates a PeriodicWorkRequest to run periodically once every 7 days. You can also set some extra constraints like execute this task only if internet connection is available. This will execute the task once in 7 days and only if device has internet connection.