penduDev
penduDev

Reputation: 4785

Should I call RESTful Api from an Activity or an IntentService?

I'm making a login post request from android phone.

Returned result will be 'success' or 'fail'.

I can make this post request using either a IntentService or an Activity, both will work fine.

Case I'm concerned about:

Phone rings (activity paused/destroyed) before receiving the result from the web service.

Will I miss the result in this case?

I want the result of web service to be saved even if the activity stops before accepting the result.

Is there anyway it'll work using Activity or do I need to receive the result using an IntentService ?

Upvotes: 0

Views: 665

Answers (2)

dawid gdanski
dawid gdanski

Reputation: 2452

Any request sent from the Activity results in NetworkOnMainThreadException being raised - you must not call any http request from UI thread (How to fix android.os.NetworkOnMainThreadException?)

Delegating the request to IntentService and notifying Activity via Broadcast (opitionally prioritized Broadcast to handle cases when your Activity is in background while the Broadcast is delivered to the receiver) is the easiest approach I think.

Alternatively, you can use AsyncTask but you must handle screen rotation and remember about task cancellation.

You can extend AsyncTaskLoader and provide your custom loader but you still must remember about request cancellation (http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html).

An third-party open source, maybe? OkHttp allows you to execute asynchronous Http requests. In addition there is a cancel() method on a Call object which executes the request. Thus, you can easily use it in the activity

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java

Indeed, the StrictMode is a good tool that validates errors during development.

Upvotes: 1

Archimedes Trajano
Archimedes Trajano

Reputation: 41220

It should be on the service, the best way of finding bad behavior like this is to enable strict mode on your application.

If you put it on the activity it will block the activity.

Upvotes: 2

Related Questions