Android best practice AsyncTask - android

I am new to Android Development. Sorry for a dumb question.
I need to check several http resources (resource1, resource2... etc) and check if they are up. If resource 1 is unavailable, then the app needs to check if internet is up (probably ping google?) and then if the connection is actually working it needs to check all the other resources and place the information about what is down to the notification drawer.
It's pretty straightforward to do it with AsyncTask and HttpURLConnection for one resource but i don't quite understand how to follow execution logic with async calls (resource1 -> google -> resource2 -> gather info in one place -> display notification). What is the best practice for it?

#FD_'s answer is valid but I think there is a better way that avoids the horrors of the Async Task. For the record I upvoted FD_'s answer as it is valid I am just pointing out another way.
So I would make a result object. This can be used to work out what happened when you tried to communicate with the various services. You could have something like
public class ResponseResult {
public String displayName; // so we know what this was all about e.g. "google request"
public boolean success;
public String message;
public int httpStatusCode; //useful to help workout what went wrong e.g. 500, 302 etc.
}
You could then use something like the Android Volley Library that is better than an AsyncTask as it uses a RequestQueue in another thread, which survives the Activity lifecycle better. It also might make your code a little easier to read/manage.
You can read a little about Volley Vs AsyncTask here - Volley and AsyncTask
Once you have issues all your requests and put the results in an Array or List, you could then iterate over them to print the result.
You can get Volley from here https://android.googlesource.com/platform/frameworks/volley
Additional Info
You might also find this inforgraphic from Robospice to be useful as it helps to explain the drawbacks of an AsyncTask.
https://raw.github.com/octo-online/robospice/master/gfx/RoboSpice-InfoGraphics.png
Another implementation
You may find this implementation is not suitable but it makes some sense and would produce even less code.
You could write some server side code to do the checks for you and return an XML/JSON array of result objects. This has the advantage of a single request to a hardwired server with a more reliable connection, that possibly could make the requests in a shorter space of time.
Your Android device would only issue a single request to the server and then process the result array per my other method above.
The major drawback is that this would introduce another set of code and additional hardware.

I would encourage using Volley library for that purpose also. Check past Google IO 2013 interesting video about it.
Advantages of using Volley:
Volley automatically schedule all network requests. It means that
Volley will be taking care of all the network requests your app
executes for fetching response or image from web.
Volley provides transparent disk and memory caching.
Volley provides powerful cancellation request API. It means that you
can cancel a single request or you can set blocks or scopes of
requests to cancel.
Volley provides powerful customization abilities.
Volley provides Debugging and tracing tools
VIDEO: Google I/O 2013 – Volley: Easy, Fast Networking for Android
**source*: http://www.technotalkative.com/android-volley-library-example/
On the other hand, once one of those resources is unavailable, you don't have to ping google as you said. Android API has facilities to check whether your mobile is connected to the Internet; something like this would be enough:
private boolean isConnectedToInternet() {
return (((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null);
}

Just perform all your logic and internet operations in one place, in the same AsyncTask. Create a class that holds all result information and implement your AsyncTask to return (eg send to a delegate/listener/call main thread method) an instance of that class.

If you like to execute your async task using similar syntax as Jquery's $ajax, this article shows you how to do it. With very little code in the article and Java 8's lambda expression, you will be able to write your async code like this:
Async.run(() -> {
//code will be executed on a background thread
MyAPI api = new MyAPI()
return api.loadData();
})
.whenComplete((data) -> {
//back on UI thread, update UI using data returned
})
.onError((ex) -> {
//handle exception on UI thread
})
.execute();

Related

Android Studio Asynctask Alternative

I'm new to Android Development, and I've run into this problem that I haven't found a solution for.
It starts off first with going to a webservice api for login. From there if the login is successful it executes to 2 functions for the actually data it needs, stores in sqlite and then proceeds to next activity. All 3 api requests are using AsyncTask and from what I understand my Activity is actually running faster than my "doInBackground" background thread. I want to know the path or what i should look into. I've read posts about using sleep, and read posts about how that is bad to do. I want to get the json data i need, store it, and use it immediately. I think i'm suppose to find away to connect directly and use a progress bar to get the data. Keep in mind, it's not a lot of data, but it's enough to stall my application.
Not sure what a ProgressBar has to do with retrieving data from a server but if you're looking for AsyncTask alternatives (particularly for HTTP calls) you can look at these frameworks (you'll probably only want to pick one):
Square's Retrofit
Google's Volley
Either one will make your life a lot easier when it comes to making HTTP requests. Their own documentation explains how to use them pretty well so I'm not going to go into how to use it here.
If you're looking for a native, lower level AsyncTask alternative, have a look at AsyncTaskLoaders. The AsyncTaskLoader essentially does exactly the same thing as an AsyncTask but they live within the life cycle of the Activity or Fragment so your code tends to be less error prone.

Using excessive amount of network calls in android

I am developing an android application that needs to communicate a lot with a remote server. For this task I wrote a class that handles all the network communication.
Do I need to make for every single method as an Asynctask? What about methods that I am dependent on for the rest of the code execution? (thus needs to be done synchronously - like waiting for an answer on registration?)
I am asking this because I already had a small app before to communicate with a remote server and I didn't use any Asynctasks, this one crashes on every method being called though.
Edit -
Meanwhile - before making a class of my own I found a great tutorial related to a google libraray that already handle that the libraray name is Volley the tutorial I looked on is this one
Yes, every network call has to asynchronous. You don't need to make every single method in you class async, but i would refactor the code in a way that only one peace of code actually does the calls and this peace has to be async. If you have following code that depends on the response from the server, then use a callback.
In pseudo code that would look something like this:
void makeNetworkCall(command, listener){
async(){
result = command.execute();
listener.onCommandSuccess(result);
}
}
Do I need to make for every single method as an Asynctask?
Yes. Android requires networking code to be executed asynchronously, so the user interface never gets blocked.
What about methods that I am dependent on for the rest of the code execution?
You can wait for an Asynchtask to finish execution. Refer to this question.

Best way to send HTTP GET requests ansynchronously in Android?

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 sporadically. I store this data in a queue and want to send it to the server in a background asynchronously without slowing down the main UI thread. Each unit of data in the queue requires a GET request. The queue has to be emptied even if the app closes.
What's the best practice to do this? Please post/direct me to code/tutorials.
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.
You could do your own async HTTP GET calls using AsyncTask but I would recommend against it unless you're doing it from a learning point of view. If you want a nice, clean and stable solution I'd suggest that you use the well known Android Asynchronous Http Client 3rd party library. From the site:
"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."
Making a GET is as easy as:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});

Android Library: Handle async http requests internally?

I'm writing an Android library that makes http requests to a bunch of different services. Currently, I have the http requests happening in an AsyncTask and calling back to an app supplied delegate with results in the onPostExecute method. So, basically the developer invokes their desired method without worrying about creating an AsyncTask.
However, I'm starting to wonder if I should be making these calls asynchronously or leave the library completely synchronous and put the responsibility on the dev to put the method calls in AsyncTasks in their apps. Is there a best practice about things like this?
From my experience of being a part of several projects with wide APIs, in most cases where we decided to provide an asynchronous API, in the end, we had to either provide additional synchronous API or make the old asynchronous API obsolete with new synchronous API.
When I write an API, I try to avoid any assumption as for the end user.
I think you'll find the following interesting (or so I hope):
How to Write Good API
If you want to be strict, put the asynchronous task in your library so the developers have no choice other than to do the request asynchronously (which is already done in your library).
But if you want to be more flexible, leave the decision to the developers whether they want to put it in asynchronous or not.
If I were you, I'll leave the decision to developers as the purpose of the library is to do the request and get the result, not how to do the request. This way, your library will fit in any developer's desire and not the other way around.
I think it is a good idea to make the calls asynchronously in your library. To notify the calling Activity when the data is received you should define in your Class an abstract method that you call inside your class after the request and processing is complete. And then the user that uses your Class will have to implement that method, and that method will be called when the processing is complete. For example:
public class ProcessingClass{
private void processData(){
//Async processing
.....
onProcessComplete();
}
public abstract void onProcessComplete(){
}
}
And then let's say inside your activity you can do something like this:
private class MyProcessingClass extends ProcessingClass{
#Override
public void onProcessComplete(){
//The task is complete...
//Update UI or something like this...
}
}

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