Best way to send HTTP GET requests ansynchronously in Android?

后端 未结 2 741
暖寄归人
暖寄归人 2021-01-31 05:59

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 s

2条回答
  •  遥遥无期
    2021-01-31 06:34

    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.

提交回复
热议问题