Creating an Android background service that continuously polls a REST API for data

twcus picture twcus · Aug 26, 2016 · Viewed 11.3k times · Source

I need to write an Android service that polls a server for data, parses the data, and then sends it to an app via intents. The polling must occur frequently (every few seconds). From what I've read, polling like this is not recommended (due to battery life concerns). This is my first time developing in Android, and after doing a lot of research there are a few things that remain unclear to me.

I am unsure if a service, sync adapter, or alarm manager would be better suited for my needs. Which of these makes most sense in the context of this problem?

This service needs to start on boot and continue to run in the background. After polling the server, the data is sent to another app via intents. The service should have no user interaction at all. From what I've read it seems like Android tries to prevent people from writing this sort of thing due to malware concerns. Is it possible to accomplish this?

Answer

Prokash Sarkar picture Prokash Sarkar · Aug 26, 2016

First of all, create a service class that will run a handler after a given time interval,

  public class SyncService extends Service {

   private Handler mHandler;
   // default interval for syncing data
    public static final long DEFAULT_SYNC_INTERVAL = 30 * 1000;

        // task to be run here
        private Runnable runnableService = new Runnable() {
            @Override
            public void run() {
                syncData();
                // Repeat this runnable code block again every ... min
                mHandler.postDelayed(runnableService, Constant.DEFAULT_SYNC_INTERVAL);
            }
        };

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Create the Handler object
            mHandler = new Handler();
            // Execute a runnable task as soon as possible
            mHandler.post(runnableService);

            return START_STICKY;
        }

        private synchronized void syncData() {
            // call your rest service here
        }
    }

Inside the syncData() method put your REST API call which will be called after a 30 sec interval.

Regarding the service startup on boot, use a broadcast receiver that will trigger the service once the boot is complete, for example,

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

The rest of the thing is up to you! Please try yourself first and ask back for help!