Android Library: Handle async http requests internally? - android

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...
}
}

Related

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.

Android best practice AsyncTask

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();

Should I use a thread or service to run tasks in the background in Android?

I'm building an Android library to collect data from the host app and send this data to an online server in the background. I realize that this would require some sort of multi-threading/use of a service/forking.
The application simply keeps adding data through library calls, and the library should handle the sending of this data in the background without disturbing the main UI.
How should I got about making this library? Should the entire library run on an Android Service? Should I just use another thread? This is my first foray into parallelism. I'm not sure what the best way to do this is.
A detailed response is appreciated.
Some of the answers aren't quite correct. Services (Android Service component) are NOT made to run in the background, they run in the default UI thread.
In all honesty, the question shouldn't be service or thread or anything. Your library does NOT need to kick start a service, it could simply be a class (singleton/static, whatever it is) that should extend AsyncTask (or anything else running in the background that I'll explain in a bit) and use the doInBackground method to send stuff to the server. Note AsyncTask is nothing but a Thread internally. So here's what I would do:
Let's call your library's main class that interfaces with your server ServerHelper. You can make this a singleton (or static but that's a separate discussion). Within this class create an innerclass say ServerHelperCommandTask and extend AsyncTask. You really should review AsyncTask in detail to understand how that works. Because you would be asked to override doInBackGround. Anything you put in this method will autmoatically get exectued in a separate thread off the UI. Then a callback is invoked called onPostExecute that you can override as you will get the result from doInBackground here. This OnPostExecute is called in the mainThread so you can check for say error results here, etc etc.
This would be the simplest method; however, there are many other methods and libraries that help you with networking and deal with all the background stuff internally. Google just release a library called Volley which you may be able to plugin and use as it would do all the parallel processing for you. But that may take a bit of learning curve. Hope you understand AsyncTasks as in your case if the data pushed isn't a lot, then AsyncTasks is the way to go. Also note that you can call multiple AsyncTasks but while that seems on the surface that it is kicking off multiple parallel threads, that isn't quite accurate since honeycomb as internally you can call 5 Asynctasks but all 5 of those tasks will be executed sequentially so you wouldn't have to worry much about serializing.
Service would be a more reliable solution for situation You described.
I mean running background threads from service, not from Activity. Service itself does not provide separate thread by default, by the way.
The point is that Services have higher priority than acitivities so they will be destroyed with less probabilty, so your long-running task won't be interrupted.
You could do both but here's pros and cons for each solution :
Services are made to run in the background, even when your app is not in the foreground. sers usually don't like having services running for nothing.
From your description it seems that you would only need to have this thread running when the app is in foreground right ?
If so, a normal thread could do the job.
However, a service might be easier to implement.
Hope it helps
You should definitely use a Service in this situation. Async tasks and manually creating a thread is not really suitable for computations that need to run in the background for network communication. Use the Async task for long running local computations (e.g. for an algorithm doing sorting).
Note that if you use a service, it will by nature NOT run as a background thread! You need to handle threading manually. In order to save yourself from this hassle (especially if it is your first time with multi-threading) use an IntentService!
The IntentService may be invoked using the startService method as with any other service, but the IntentService class is able to handle multiple invocations as in a producer/consumer pattern. This means that you can queue commands automatically to the service just using the startService method. In the IntentService class that you make, you can then handle different types of commands by looking at the given action inside of the intent that is sent along as a parameter in the startService method.
Here is an example of how the implementation of an IntentService:
public class SimpleIntentService extends IntentService {
public SimpleIntentService() {
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
String commnad = intent.getAction();
//handle your command here and execute your desired code depending on this command
}
}

Synchronous service calls in Android

I'm working on application whose main responsibility is to contact remote server and display the data provided.
Service is Soap based. For that I use ksoap library, but let's cut to the case.
I've been "calling service" with the use of asynchronous tasks.
Everything seemed to go well, but...
Service is sequential, and tends to 'lose' my requests, so I don't get proper results.
So I decided to take a synchronous approach to resolve the issue, but this way I have to provide additional loading buttons/bars etc.
The performance is terrible in this way. What is the best way to handle such case ?
What kind of synchronisation can I use so there won't be any race between the requests ?
How can I make use of Android Services ?
How are those better?
Thank you in advance for answers.
You can actually call the AsyncTask in a sync way:
class MyTask extends AsyncTask<Void,Void,String>
{...}
MyTask x = new MyTask();
String result = x.execute().get();
See the docs page for AsyncTask

connecting to a webservice from android - AsyncTask or Service?

I'm writing an android app that will connect to a REST/JSON webservice. Users will be retrieving information, uploading comments, downloading and uploading images etc.
I know that I shouldn't keep all this network communication in the Activity/UI thread, as it will cause ANRs. What I'm confused about is whether I should use an AsyncTask or a Service with "manual" threading to accomplish this;
With a Service, I'd simply have a public method for each method in the webservice's API. I'd then implement threading within each of these methods.
If I used an AsyncTask, I would create a helper class that defined AsyncTasks for each method in the webservice's API.
Which method is preferred? Interaction with the webservice will only happen while the user is in the Activity. Once they switch to another application, or exit the program, there is no need for communication with the webservice.
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks of the UI-thread.
It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.
I recommend IntentService, it is not much more complex to implement and is definitely more robust because it is not tied so closely on the ActivityLifecycle (in particular to onConfigurationChange())
This library provides an async wrapper to Apache httpclient available in Android.
http://loopj.com/android-async-http/

Categories

Resources