Multiple HTTP POST in sequence - android

I have an app underdevelopment and I need to do 3 HTTP POSTs in sequence. What is the best way to implement this ? Should I
Make each HTTP Post in it own Async Class and daisy chain the Async classes(i.e. call the second async from the onPostExecute of the first Async)
Put all the HTTP POSTs in the doInBcakGround of a single Async.
I know how to do a HTTP POST request and I am using the OKHTTP lib. I just would like to know that the best practice it for multiple POSTs in sequence.
Cheers

Your first approach will be better and quite modular as you can keep the track of anything in your application.In the three different AsyncTask you can have a check in postExceute() that which AsyncTask is done with its work (more easily and precisely) AND
>>>>>In case if the application gets Crashed
then which of the httpPost failed. However , the second one will make your code messy and you will be unable to track on getting Exception that which httpPost request failed(in a straight forward way though).
So Launching your second AsyncTask from onPostExecute of your first task will be better approach.
See here too : Calling an AsyncTask from another AsyncTask

Both 1 and 2 approaches make app ANR, so better to for other approach.
You can use ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
here is more deatias
http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html

Put all the HTTP POSTs in the doInBcakGround of a single Async.
because all your posts handle in one module.
dose not have overhead of creating asyntask and GC may not call as many as your first.
you do not need to check internet connection 3 times you have to check it one time
all exception handles one time but in approach 1 you have to copy and paste all exception handler that may occurs. and always recommended not to repeat yourself. if you can do something to not copy and paste codes, do it.
At the end I prefer approach 2.

Related

What makes retrofit faster than HttpUrlConnection + AsyncTask?

The following blog gives comparison between the speed of the various Android Async Http Clients. Can someone explain what makes retrofit so ridiculously fast?
EDIT: After going through the blog post again, the single-vs-multi thread issue might not be true. The problem is that they didn't share the gory details of their profiling/benchmarking; that single set of numbers doesn't provide much insight. They state, "we determined that retrieving data from the API (the networking) was the bottleneck" but they don't break that down much. Did they make all the Volley and Retrofit requests single-threaded? Did they try to multi-thread their AsyncTasks so they could compare apples to apples? They don't specify.
If parsing a response into a JSONObject is slowing your app, one approach I have taken is using a JSONReader to parse the response in an event-driven manner. This may involve more code, but the benefit is that you get fine-grained control, so you can skip over things and not waste cycles parsing values that you don't care about. Depending on your application, this alone could speed things up quite a bit.
Personally, I find their assertion that Retrofit is easier to use as a more compelling reason to choose it for handling server access in my app.
From the AsyncTask doc under "Order of Execution":
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
This means that each request is waiting not only for the previous request to complete, but for all its JSON to be read/parsed as well.
Whereas AsyncTask is by default single-threaded, Retrofit is not. For the test to be fair, they should have used the ThreadPoolExecutor for the AsyncTasks. Not pointing out this distinction borders on disingenuous. I'd be very surprised that they were not aware of the single-threaded nature of AsyncTask.

What is the best practice for a multiple request at same time

I have to send four different request in an api at the same time. Do i need to make AsyncTask background thread for each request or all request could be done through a single AsyncTask. Can somebody please help.
This is a concurrency issue. There is literally dozens of ways to do this in Android. I've written almost every single one for courses that cover this material... and even then it isn't 'simple'.
I'd personally make use of HaMeR (Handler, Messages, Runnable) framework of Android. Create 4 runnables and have them post their results to a Handler.
However... That isn't the easiest to implement. and would require you to understand how to safely create your own custom handler (making use of WeakReference properly, etc.)
Therefore, I'd recommend running the asyncTask(s) on the executorService
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); The default thread pool executor should start with 4 threads (I believe off-hand without looking it up).
I am assuming you are using HttpURLConnections. Unfortunately each of those connections, as specified in the documentation, is capable of handling only a single request.
However, you can (and possibly should) still perform all your requests in a single AsyncTask. Each AsyncTask will require the creation of a new thread which takes lots of time and resources. So don't listen to anyone who tells you to create a new task for each request.
You also have the option of exploiting HTTP persistence. If you add the header Connection: Keep-Alive to your request via connection.setRequestProperty("Connection", "Keep-Alive");, you will be able to send multiple requests over the same connection and save a lot of time and resources.
It's a little complicated in Java, because of the one-request-per-httpurlconnection rule, but it can be done. First, when you are done with your first request's HttpURLConnection do not close that connection. Then, to create the next connection, call url.openConnection() on the same URL object that you used to create your first HttpURLConnection. The JVM will know to reuse that connection if possible to save bandwidth.
You also have the option of using HTTP/2.0 multiplexing, which allows you to send multiple requests literally at the same time. Unfortunately I am not yet well versed enough in HTTP/2.0 to tell you exactly how to make use of this, but the multiplexing feature was included to solve exactly this problem.

should you create new Async Tasks for every different call or use the same one

So I have an app that will make multipe HTTP Post/Gets
E.G. Login, getThisData, getThatData, sendThis, sendThat
Is it better to have a seperate AsyncTask to handle each one
Or one async task and process them differently with a switch in onPostExecute and doInBackground
Cheers
Short answer is yes you should create a new AsncTask for each call.
And if you interested, the long answer is;
According to the Android's Asynctask documentation,
The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.
The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Happy asynchronous coding! :-)
It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async.
Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.
You'll probably want to separate them, especially if their functionality in the pre/post executes differs. Try to organize your code into logical blocks. For example, if you have an Async Task to Login, and an Async task to, for example, download lots of document data via JSON, they will want separate Async tasks.
However, lets say you have two separate API calls that return similar or partially the same data - if one returned the details of a file (name, size) and the other returned the same data but was a revision of a file - you could switch these in the same ASYNC because the post execute is going to perform the same (or partially the same) code to extract data from the JSON.
If you want to create one instance of AsyncTask, and execute() it several times, no:
Execute AsyncTask several times
If you are asking about designing: whether you should write one class to get different kind of data? It really depends on your circumstances:
If these HTTP call supposed to be sequential, you can put them in one AsyncTask class.
If they have lot in common, just point to different URIs, you can write a call(String uri) method, and invoke that method in your AsyncTask. This case, I think one AsyncTask is also enough.

AsyncTask v/s ThreadPoolExecutor for network request

I am working on a project where i need to hit a web service download the data which is JSON and will be represented in a list. And all the list items have there thumbnail url's which would be downloaded and displayed in the list item.
I have done the entire calling part with both a ThreadPoolExecutor and a AsyncTask.
But from a design perspective which is a better option out of:
1. ThreadPoolExecutor
2. AsyncTask
Few adv. of ThreadPoolExecutor:
1. User can define no. of concurrent threads that can be executed.
2. Cancelling all the request at once.
Few adv. of AsyncTask:
1. Internally it uses a ThreadPoolExecutor, however we cant define no. of threads that run simultaneously.
2. Cancelling a single request is easy.
3. Ability to attach and detach a task.
4. Updating the UI from doInBackground is simple.
I know more advantages of AsyncTask, however for a simple application like fetching data from a web service and later on fetching images.
Which would be more appropriate a AsyncTask or ThreadPoolExecutor? If you can provide a few reasons regarding your choice it would be helpful.
I have read a few article here on SO but none that compares the two. If there are any that i missed sorry for the trouble could you please post me the link for the same.
Thanks in advance.
I consider that AsyncTask is useful if you want to load thumbnail using a series "cascade-call": in the onPostExecute, you can start the next AsyncTask to download the next thumbnail.
But if you want to improve efficiency, I suggest using ThreadPoolExecutor. This is a sentence from developer.android.com:
Thread pools address two different problems: they usually provide
improved performance when executing large numbers of asynchronous
tasks, due to reduced per-task invocation overhead, and they provide a
means of bounding and managing the resources, including threads,
consumed when executing a collection of tasks. Each ThreadPoolExecutor
also maintains some basic statistics, such as the number of completed
tasks.
In conclusion, ThreadPoolExecutor was probably designed for cases such as your; for this reason, I suggest you this class.

Implementing asynchronous http requests on Android with AsyncTask

I'm building this client for a web service.
Pretty much everything makes requests to a server and now what I do is, I open a new thread and put all my requests in the same thread. That means I'm making all my requests in a serial way inside the thread and that turns into a lot of waiting for the user. Aiming to make the application faster, I want to make every server request in an asynchronous way.
I have a Networking class that handles all the HTTP requests I need and I'm thinking of making it so that every request starts its own thread.
I'm thinking of using ASyncTask for this but I noticed that with ASyncTask I'd need a class for each of my http requests (a class for GET, POST, PUT, etc). Is that the best way of doing it? is there a more efficient/clean way of doing this? What do you guys suggest.
Seems like a design decision that will depend on exactly what you are up to. There are various ways in Android to execute tasks depending on whether the user is waiting for some data or is being notified later on once the background task completes.
I would suggest you to look at this post that compares various task mechanisms in Android. Apart from this also go through the java.util.concurrent package.
I'm sorry this is not a concrete answer, but take it from me - it mostly depends on how are you trying to serve the user. So one can only suggest ideas. Hope this helps.

Categories

Resources