Search code examples
androidretrofitrx-javaandroid-networkingandroid-intentservice

Is there any development pattern that can replace an IntentService for network requests?


In the current app that I am developing with a co-worker, we're using IntentServices with Volley calls inside to process RESTful API network requests. It's just simple JSON string data, and some small images.

My question to those experienced in processing network requests is this: is there something more appropriate, or cleaner to implement out there?

From what I understand, the advantage of using an IntentService is that it runs in the background off the main thread, and is typically one of the last things killed by the Android OS. The downside being that IntentServices are run sequentially.

I've been reading a lot about RxJava, and Retrofit, and feel like our needs could be better served with that combination. Retrofit may be enough on its own, but I'd really appreciate some third-party insight.


Solution

  • My general rule of thumb is:

    • If the network I/O should be under a second, and you don't mind if it does not run to completion, any asynchronous option should be fine.

    • If the network I/O should be more than a second, or you really want to increase the odds that it will run to completion, use a Service. Whether you use IntentService or some other Service implementation is up to you, but you want to have a Service as an indicator to the OS that you're doing work, so it doesn't terminate your process quite so quickly once your app moves to the background. Remember that "moves to the background" is not always something initiated directly by the user, as incoming phone calls and such also move you to the background.

    • If the network I/O will take more than 15 seconds, not only do you need to use a Service, but you need to think about a WakeLock (via my WakefulIntentService, or WakefulBroadcastReceiver, or your own carefully-managed WakeLock) and possibly a WifiLock. 15 seconds is the minimum auto-screen-off period in Settings, which is where that figure comes from.

    With all that in mind:

    The downside being that IntentServices are run sequentially.

    I am translating this as "an IntentService has a single thread for processing requests". This is true. In cases where you need a Service and you need parallel processing, create your own Service. Just be sure to call stopSelf() when you have no outstanding work.

    I've been reading a lot about RxJava, and Retrofit, and feel like our needs could be better served with that combination

    This has nothing to do with whether or not you use a Service. Just don't try doing asynchronous stuff (e.g., a Retrofit call using a Callback) from an IntentService, as you defeat the purpose of the IntentService (indicating to the OS that you're doing work). So, from an IntentService, you would use Retrofit's synchronous API, sans a Callback.