Implementing asynchronous http requests on Android with AsyncTask - android

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.

Related

Asynchronous requests to server posted in a loop - Android

I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!

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.

Performing multiple Network Operations in a Service

quick question, Whats the best way to perform multiple network operations on a service. Consider something like a weather service where one has to update periodically. for each time, i call in this order
getCurrentWeather();
getForecast();
getForecasthours()
which makes a Http request and obtains data in JSON. This returns a new JSON Object for each method which is used to update the UI. Now sometimes, we are not sure how long one of this operations might take, so is using multiple AsyncTasks in a Service a better way to go about this? or is this sufficient enough or are there other better ways to do this. Many Thanks
Async task is a good way. But there are more frameworks that have more features for making json http requests.
Have a look at Google Volley framework.
https://github.com/mcxiaoke/android-volley

what is better? many AsyncTasks or one to handle all AsyncRequest?

currently I have an app that creates all sorts of different requests to Facebook and my server, and I was wondering if the best way to do this is implementing a different AsyncTask or using the same AsyncTask for all the different requests.
what do you think?
Here is a use-case for instance:
I send a Facebook connect request, when I get to onComplete, I get the users Information with FQL (has to be Asynchronous) , when the response comes back, the user's image is posted on the main view.
After this, the app sends a different request to the app's background server and gets a response.
I think you must decide it for yourself.
If you have lots of requests beware of the android's limitation of number of AsyncTasks. If you hit that limit your app will crash.
Also notice that if you assign many jobs to a single AsyncTask you could have a very long running task on the background.
You can also read this article -> The Hidden Pitfalls of AsyncTask.
I'd suggest to use concurrent AsyncTasks to ensure all the other requests are run in case one of them won't return an answer.

How should I make multiple http requests in android

Hey I am trying to make multiple http requests and wondering the best way to perform this in android. Currently I am using an IntentService with threads, however this doesnt work too well because onhandleintent returns before the threading is complete. Should I Switch to A regular service and start my own threads in there or would asyncTask be more approiate?
Thanks
Any time you deal with threads you're going to have to deal with synchronization. For example, when onHandleIntent() is called you may need to synchronize with your HTTP request thread(s) and wait for it to complete.
If you know ahead of time you will be doing this a lot it may be worth looking at something like ThreadPoolExecutor to save a bit on the pains of creating and tearing down threads. Again you will still need to synchronize your threads if you want to wait for their termination before moving on. Android has many ways of doing this including abstractions that make it fairly trivial to implement.
If you're already starting new threads anyway (whether directly or indirectly), then yes you should use a Service instead of an IntentService. The whole point of an IntentService is for it to handle threading for you.

Categories

Resources