androidrestcachinghttprequestrequest-queueing

Store HTTP/REST requests in case no connection is available


I am currently developing an android application using HTTP/REST requests to communicate with my backend. I am not using any particular library yet since until now the built-in HttpURLConnection works fine for me. However I would like to have some kind of fallback mechanism if my requests fail due connectivity issues. A similiar problem is also described in https://stackoverflow.com/questions/31786486/android-volley-internet-queue but has not been answered yet and other related posts rather focus on caching older responses to redirect requests to the cache when there is no connection is available.

Up to now I considered using Volley but as far as I understand it it only allows to retry a failed request until it finally connects. I think it would be a cleaner solution to cache the failed request and attempt to resend it after I registered a change in my connectivity state via a BroadcastReceiver. Is there an existing solution which does that for me or do I have to set up an internal database and manage the whole process myself ?

TL;DR

I want to store failed HTTP/REST requests on my android device when my device is offline and resend them when the device can establish a connection again. What am I looking for ?


Solution

  • I had the same situation with a reporting service. What I implemented was a Service that receives requests and queues them. In a separate thread (started when the service starts) it checks the queue and attempts to make the connection. If you use a BlockingQueue you have the 'signalling' between threads for free, so you don't need to idle-poll.

    You can use set up a receiver for WifiManager.WIFI_STATE_CHANGED_ACTION and/or ConnectivityManager.CONNECTIVITY_ACTION events, so that you start the service or wake up the thread and attempt to re-send when the connection is up again.

    I suggest a Service so you can detach all this from the code in your Activities and have some facilities for starting and stopping it. I personally used an IntentService because that allows me to serialize the requests through Intents, and let the OS handle the Intent management sending for me. You might implement it differently, even without a Service, just with a Singleton object.

    If you also need storing them when your app is not running, I would use a SQLite Database.