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.
Related
I want to control a RaspberryPi via android app and plan to do this by defining an api on the raspberry and accessing it via the app.
On the Android Developer Guides I found the recommendation to implement a DownloadCallback interface.
My question is, why would I want to do that, if I can alternatively simply use an AsyncTask and make an HttpRequest?
Using an AsyncTask for network calls is considered a bad idea. First, AsyncTask does not handle orientation correctly so you need to have more code put in so that the asynctask properly terminates (making sure it doesn't make calls to the finishing activity, making sure it doesn't hold any strong references to the finishing activity). You also cannot halt AsyncTask so lets say in your main UI thread, you want to stop the AsyncTask from performing the network call but you already started it. Well you are out of luck and you need to wait until it terminates on its own. (As mentioned in the comment below, this is not true. You can halt interrupt the thread of the AsyncTask to "cancel") Also, you cannot make parallel network requests in an AsyncTask easily.
Also this is more of a preference but using AsyncTask is more boilerplate code than I would like. Retrofit is my most preferred way of network operations.
DownloadCallback isn't about replacing the AsyncTask. It is just a way to communicate between your fragment (the one who started the network call) and the activity (the one who wants to know what the progress of the network call is) about the progress of your network operations. You can see here https://developer.android.com/training/basics/network-ops/connecting that they are still using AsyncTask for network operations but they are using the DownloadCallback to notify the activity about the progress of your operation.
I have 21 API calls that need to be made once the app gets to the splash screen. What my app does is as follows:
a> Make API call using retrofit's enqueue method.
b> once the response is available(call success) it stores data to local database using greendao. Inside app it only uses data from greendao databases. What I need is to keep track of the api call whether it failed or not. If failed retry. Also if there is a way to chain the requests can anyone mention them? I looked into rxjava which allows chaining upto 2 or 3 apis (as far as I know). Any help is much appreciated.
You can create IntentService which will run call.execute() code one by one.
This way you will call synchronous call to all apis.
Once all request completes send broadcast to activity or communicate with activity through other mechanism.
I have a two part question. Both are somewhat general.
I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.
Hopefully that wasn't too abstract. Thanks in advance.
Yes, Service is the way to go, but a started service, not a bound one.
You could make async request methods, and the Service can broadcast the result back to your Activity.
The async request in this case is a startService(intent) with an
Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
And the reply is a broadcast by the Service with the relevant data.
This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.
To start, you should get yourself familiar with these topics:
Started Services (for the requests)
LocalBroadcastReceiver (for the reply)
Event Bus (alternative to LocalBroadcastReceiver, for example Otto)
I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!
1)If you need code to run even when your Activity isn't, the correct answer is a Service. If you just need to cache data, then storing it in a global static variable somewhere may be ok.
2)Your service can start a Thread or AsyncTask. These execute in parallel. onStartCommand generally launches it in this case.
As with most things, the answer to these questions are subjective at best. I would need more information then I currently have, but I'll take a vague, general stab at this...
If you need something persistently hitting your server repeatedly I would say use a service.
Where you call it is not nearly as important as how many times it needs to be called. That being said the answer is yes. If you need this data as soon as the application or activity loads, then the onCreate method is where it needs to be loaded.
My reccomendation is either A) service or B)AsyncTask.
Go with A if you have to hit the server repeatedly for data and need it in regular intervals. Otherwise go with an AsyncTask and load all the data you need into an object for storage. Then you can use it as you need and it will essentially be "cached".
The difference between the two is simply "best tool for the job". I see you use some javascript. To give a proper analogy, using a service for a server call rather than an async task, is the equivalent of using a web socket (node js) when you could of just used an ajax call. Hope this helps. Oh and PS, please don't use static variables in 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...
}
}
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/