In an Android app, I have to make multiple GET requests to a URL in order to transmit data to an external server (that's how the third party API works).
Data comes in sporadically. I store this data in a queue and want to send it to the server in a background asynchronously without slowing down the main UI thread. Each unit of data in the queue requires a GET request. The queue has to be emptied even if the app closes.
What's the best practice to do this? Please post/direct me to code/tutorials.
What's the best practice to do this?
That would depend on what "this" is and where this work is being done.
If "this" is "asynchronous work", you will use threads in one form or fashion:
If your HTTP operations are driving a UI, you might use AsyncTask
, so you can update the UI safely from onPostExecute()
If your HTTP operations are purely in the background, and you want to do one at a time, use an IntentService
, which has its own background thread and work queue
If your HTTP operations are purely in the background, and you want to do one at at time, and you are concerned about ensuring that the device should stay awake while all this is going on, consider my WakefulIntentService
If your HTTP operations are purely in the background, but you feel that you want to do several at a time, roll your own Service
that uses an Executor
with your own thread pool, making sure that you shut down that service when the work is done (as IntentService
does), and making sure that the device stays awake with a WakeLock
(and perhaps a WifiLock
)
Etc.
If "this" is "HTTP GET" requests, use:
HttpUrlConnection
, or
HttpClient
, or
OkHttp (wrapper around those with added benefits), or
Retrofit (if your GET requests are really Web service calls), or
Volley (if you like your HTTP wrapper code to be undocumented, unsupported, but Googly)
Any number of other third-party wrapper libraries
If "this" is "queue", use the Queue
class, or LinkedBlockingQueue
if you plan on having multiple threads work with it at once.
If "this" is something else, I can't help you, as I'm tired of guessing.