Perform REST call from background in android after fixed interval

android background service http request
android send data to server in background
how to call api in background in android
send data from activity to running service android
android background execution
android run in background
background fetch android
background process in android studio

I am new to Android, I want to know the most efficient way to perform a background operation which is a simple POST request with JSON Body which will be hit after a fixed interval. Which is best way, Intent Service Or Async Task.

Create a JobScheduler as below

 public static void scheduleJob(Context context) {
        ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
        builder.setMinimumLatency(1 * 1000); // wait at least
        builder.setOverrideDeadline(3 * 1000); // maximum delay
        charging or not
        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    }

Create the following receiver

public class MyStartServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Util.scheduleJob(context);
    }
}

Register the receiver in the Android manifest for the BOOT_COMPLETED event.

<receiver android:name="MyStartServiceReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Create a JobService and add your code in to onStartJob

public class TestJobService extends JobService {
    private static final String TAG = "SyncService";

    @Override
    public boolean onStartJob(JobParameters params) {
        Intent service = new Intent(getApplicationContext(), LocalWordService.class);
        getApplicationContext().startService(service);
        Util.scheduleJob(getApplicationContext()); // reschedule the job
        return true;
    }

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

}

For more details refer : linkhere

Send work requests to the background service, I am new to Android, I want to know the most efficient way to perform a background operation which is a simple POST request with JSON Body  handler.postDelayed(task, time); will only execute once, if you want the code to trigger at regular intervals I would suggest a Timer and a TimerTask instead of a Handler and a Runnable. TimerTasks can be set to run once, every x seconds, or with a fixed period e.g. x seconds - however long it took to run last time.

Please refer this link: https://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService

Please check my custom class example below. This will execute every 2 seconds.

class CustomThreadExecutor {

    private lateinit var scheduledExecutorService: ScheduledExecutorService
    private lateinit var scheduledFuture: ScheduledFuture<*>

    init {
        //Start Scheduler as required
        startScheduler()
    }


    fun startScheduler() {
        scheduledExecutorService = Executors.newScheduledThreadPool(2)

        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(
                { tempImageFetch() }, 0, 2, TimeUnit.SECONDS)
    }

    fun shutdownScheduler() {
        //Stop before exit the app or when necessary
        scheduledExecutorService.shutdownNow()

    }

    private fun tempImageFetch() {
        //TODO call API
    }
}

How to Schedule a Task to Run in an Interval, The next step is to report the results of the work request back to the originating Activity or Fragment. The next lesson shows you how to do this with  Periodically your Android application might need to perform a task, such as checking a server for updates. The AlarmManager class can be used to schedule and execute operations that need to occur

You can use FirebaseJobDispatcher for API level below and above Lollipop. Here is the github link:

https://github.com/firebase/firebase-jobdispatcher-android

How to implement:

Add the following to your build.gradle's dependencies section:

    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

Make a class for your job service:

    public class MyJobService extends JobService {
        @Override
        public boolean onStartJob(JobParameters job) {
            // Do some work here

            return false; // Answers the question: "Is there still work going on?"
        }

        @Override
        public boolean onStopJob(JobParameters job) {
            return false; // Answers the question: "Should this job be retried?"
        }
    }

Add this on Manifest:

<service
    android:exported="false"
    android:name=".MyJobService">
    <intent-filter>
        <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
    </intent-filter>
</service>

Add this on your main activity onCreate method:

    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

    Bundle myExtrasBundle = new Bundle();
    myExtrasBundle.putString("some_key", "some_value");

    Job myJob = dispatcher.newJobBuilder()
        // the JobService that will be called
        .setService(MyJobService.class)
        // uniquely identifies the job
        .setTag("my-unique-tag")
        // one-off job
        .setRecurring(false)
        // don't persist past a device reboot
        .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
        // start between 0 and 60 seconds from now
        .setTrigger(Trigger.executionWindow(0, 60))
        // don't overwrite an existing job with the same tag
        .setReplaceCurrent(false)
        // retry with exponential backoff
        .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
        // constraints that need to be satisfied for the job to run
        .setConstraints(
            // only run on an unmetered network
            Constraint.ON_UNMETERED_NETWORK,
            // only run when the device is charging
            Constraint.DEVICE_CHARGING
        )
        .setExtras(myExtrasBundle)
        .build();

    dispatcher.mustSchedule(myJob);

If your application is for API level Lollipop and above, then you should use JobScheduler or WorkManager

For workmanager:

https://codelabs.developers.google.com/codelabs/android-workmanager/

For JobScheduler:

http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html

8 ways to do asynchronous processing in Android and counting, In this tutorial, you'll learn three ways to run a task in the background during an The example can be, service running in the background for cleanup of application just like, we have the Java Garbage collection. public static void main(String[] args) { How Can Perform Monkey Testing in Android App? An example of using Java Timer to do something after 5 seconds. These can be used to schedule some processing on a background thread. There are other ways to handle the same in Android, you could use a Handler with postDelayed or Handler with sendMessageDelayed() and the handler can run on a background thread as shown above.

Schedule tasks and jobs intelligently in Android, Android provides several API's to do asynchronous processing, compound these or Android AsyncTasks for everything since they are well known and can do for long running operations and also, if the app is in the background and the app is Also keep in mind, if your update intervals are small and your processing is  Creating a never ending background service in Android is simple but not obvious. Android has two ways of working: foreground (the app that you use and manipulate) and background (the services that you do not see but that provide data to the apps). Not every app has a background service but some do.

Android Retrofit Call Every X Seconds, To schedule background work, Android introduced several APIs which “We should only use AlarmManager API for tasks that must execute at a Use Case: Let's say we want to perform a task after 1 hour or every 1 hour. Repeating periodic tasks within an application is a common requirement. This functionality can be used for polling new data from the network, running manual animations, or simply updating the UI. There are at least four ways to run periodic tasks: ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool.

WorkManager Periodicity - Android Developers, Handlers are used to communicate/pass data from the background thread to the UI thread. Using RxJava we can do much more than that and very easily as well, using RxJava Calling Retrofit service after certain intervals is fairly common in applications that import static com.journaldev.androidretrofitcalleveryxsecond. I am new in android development and now my launcher activity show only 5 seconds and after that I want to check the user is logged in or not function and perform the actions. here is my code.

Comments
  • From android 26, you have to use job scheduler. services are no longer an option to perform long running background operations.
  • will this work in background even after killing application and device reboot ?
  • The job is getting scheduled once, then I have to cancel the job again and then it cancels and then again onStartJob is called.
  • github.com/firebase/firebase-jobdispatcher-android/issues/131 Facing this issue
  • when onStartJob() is called, inside onStartJob() call this jobScheduler = (JobScheduler)this.getSystemService(Context.JOB_SCHEDULER_SERVICE ); jobScheduler.cancelAll();