I want to better understand how to structure an Android app where an activity fires off an API call (for example).
I'd currently implement it by putting the API call into an AsyncTask subclass, passing it a reference to the activity so it can update the UI in onPostExecute. But my gut-feel is that this is creating overly-coupled code.
I'm wondering whether instead I should put an API call like that into a service, and use a BroadcastReceiver to update the activity.
What say you, AsyncTask, or BroadcastReceiver?
I usually follow the Local Service pattern. I have a strong suspicion that this is how the official Twitter app works and that this is the pattern most of the Google apps use. This also solves the issue of your app going away (getting killed or going into the background) before the task finishes, or if the phone switches configuration during a background task.
BroadcastReceiver and service is an overhead here. A request to web-service should not go to long. Service is appropriate in case of downloading files or something similar.
AsyncTask way is the right one here. But I would suggest you showing a progress dialog to let user know that your application isn't freezed, but doing some useful work.
See the example here.
AsyncTask is just fine. Only thing you should worry about is referencing you Activity using WeakReference to avoid whole Activity be memory leaked. It isn't overly-coupled code imo if you using observer or events patterns.
I would go with a service only if the call is going to take long, so that the user can leave the app while it's completing.
I'd use the AsyncTask if the task is short enough that it almost wouldn't go ANR if done in UI thread.
(disclaimer: I consider myself a beginner, and I'm expecting comments from more experienced people)
Related
What would be the best approach for download on Android. You would be using AsyncTask or Service. I see several example being made of two ways, but what would be the best approach?
That's not the right question to ask, and the answer may be both. An AsyncTask is a separate thread of execution. A Service is just a piece of your app that runs in the background and can live past the end of an Activity.
You need to download any files on a non-UI thread, so either a Thread or AsyncTask is necessary whether you use a Service or not. So you'll always use one of those two. The question of whether or not to also use a service is a question of whether you need the file downloaded even if the user goes to another Activity (there's a few other reasons why you may want to use a Service, but this is the main one).
i suggest ,it depends upon the size of file.for small content file ,asynch is great but if is gonna be a longer task then you can go for service because service also comes with restart feature (start_sticky) in case user kill your app or your app got killed by the android os(LMK : low memory killer) in case of memory crises
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 am posting images using JSON. Whenever I take a picture i have to call the webservice.
This webservice call may take some time. I dont want to use Thread nor Asynchronous Task for this.
I want to call the Webservice in background and able to perform operations in foreground(button click, entering some data in edittext etc).
I guess this can be achieved by using Service. Please provide me some tutorials for this.
Is there any way?
Thanks in advance.
Services are basically used when we want to run some code in background even when a application or the present activity gets closed. Use Services only if you need it and be sure to destroy it when you are done otherwise you will waste memory and that is not good.
Here are some great tutorials of implementing service. Firstly make some sample codes to learn how to handle services and see their lifecycle, etc. and then try to implement them in you code otherwise you may be confused xamarin.com vogella.com and technotopia.com. Happy Coding!!!
If you need to handle upload within a serial queue service, take a look at IntentService.
and implement the abstracted onHandleIntent() method.
I'm very new to android technologies. I've recently read that android only allows a REST web service invocation from inside an AsyncTask... Is this true?? I'm developing an app for the university, I have to finish it for tomorrow and I would realy like to know if I can just call the REST WS inside an ordinary function, despite the fact that it may not be a good practice...
Thank you in advice!!
José.
The main thing is that you may not call it on the UI-thread (otherwise you will get an exception). Besides this restriction, it does not matter from where you call it.
A benefit of using AsyncTasks is that they are a very easy way of using additional threads in Android, since it comes with many callbacks (which are run on the UI-thread)
Another alternative could be to use an ExecutorService.
I need a little information/help/suggestions how can I build my application so I can use one AsyncTask from all activities which will download some data over internet. The problem is that once I run the asynctask from one activity, I want to download whole information again but to update only the information which I'm showing in that activity (like listviews, showing the images and etc.). And I'm not really sure how can I code this.
If anyone can offer me some help/suggestions even example it would be great!
Thanks a lot!
The most common way we use AsyncTask is defined it as a inner class of a Activity. By doing this, we bind the AsyncTask's life cycle to its master - Activity, As we know, the Activity's life cycle is quite transient and usually get created/destroyed many times during application running time. So...
how can I build my application so I can use one AsyncTask from all activities which will download some data over internet
In my opinion, the most reasonable solution here is Service, obviously service has a more solid life cycle than Activity/AsyncTask. You can implement a service that download data in thread, make it keep running during application running time, and update your current foreground activity's UI stuff from service. check out more details in this SO question.
Hope that help.