Android: how to poll server every 10 seconds

By , last updated July 16, 2019

In this tutorial we will show how to create a Java Service in an Android application that will poll a server every 10 seconds and how to get a response.

There are a number of ways we can fetch data from the server. Many of them are not suitable for a task of polling a server very often.

Let’s take a look at different solutions and whether we can use them in our Android application:

  Service IntentService Thread AsyncTask
What is it? An application component that performs long-running operations. An application component that performs one operation on a single background thread. A sequence of programming instructions. A class that allows to perform short background operations.
Runs On (thread) Main Thread Separate worker thread Its own thread Worker thread
Limitations Blocks the main thread Killed after the task is completed. Manual thread management. Killed after the task is completed.

To poll a server as often as every 10 seconds we need to choose a solution that will:

  1. Run for a long time
  2. Won’t be killed by the app
  3. Will run in the background and won’t block the main thread

For the purpose of this application we chose a combination of a Service and an AsyncTask.

The reason for us to use an AsyncTask in addition to a Service is that Service blocks the main thread in Android apps. It is also not allowed to perform network operations on a main thread in Android. This will result in a android.os.NetworkOnMainThreadException exception.

Android Service

Let’s create our Service. Here is a basic example of an Android Service class in Java:

public class SyncService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        stopSelf();
        super.onDestroy();
    }

}

To start and stop the Service in your Activity or other places call startService() and stopService() methods:

startService(new Intent(getApplicationContext(), SyncService.class));
stopService(new Intent(getApplicationContext(), SyncService.class));

Android handler

Android Handler is a class that will help us to schedule messages every 10 seconds.

You may also have heard about an AlarmManager. It is not advised to use AlarmManager for time intervals less than a couple of minutes.

Let’s create a Handler object and a runnableService variable that will dispatch the message every 10 seconds:

public class SyncService extends Service {

    private Handler handler;

    public static final long DEFAULT_SYNC_INTERVAL = 10 * 1000;

    private Runnable runnableService = new Runnable() {
        @Override
        public void run() {
            //create AsyncTask here 

            handler.postDelayed(runnableService, DEFAULT_SYNC_INTERVAL);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            handler = new Handler();
            handler.post(runnableService);
        }

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(runnableService);
        stopSelf();
        super.onDestroy();
    }

}

Don’t forget to remove the handler’s callbacks in an onDestroy() method or your Service won’t be able to stop.

AsyncTask

In order for our service to poll the server in the background, we will create an AsyncTask class that will do the fetching operation in it’s own worker thread the background.

Here is a simple basic Android AsyncTask class example. It has a doInBackground() method that will dispatch a request to the server and a onPostExecute() method that will receive the server response.

public class MyAsyncTask extends AsyncTask<Void, Void, HttpResult> {
    
    @Override
    protected HttpResult doInBackground(Void... v) {
        HttpRequest request = //create your request object here
        return request.execute();
    }

    protected void onPostExecute(HttpResult result) {
        if (result.getResponse() != null) {
            String response = result.getResponse();

            //do stuff with the response here

        }
    }
}

Inside the run() method of SyncService create a new AsyncTAsk each time the server should receive a request:

MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();

Now you are all set!