Android Asyntask for web service - android

I'am developing an application which is totally based on fetching data from web services.
In one activity I have to call almost 5 6 different web services which displays different information. This application is target v 2.3 to 4.x, as there are no network communication allowed on main ui thread so I am making 5 6 AsyncTask classes, because its post execute helps me a lot in displaying.
Now I am confused is this approach right or wrong, making 5 6 AsyncTask classes(can't reduce the number of web services or call in one AsyncTask because I have to check data again and again). Is this a good approach or should I change my pattern, and then switch to what approach.
Using this approach my application is working very nice and smooth on all devices.

I think that's a good pattern. It fits nicely into Object-Oriented design and each one performs it's own task.
If your web calls are all directly after each other, you could combine them into one huge AsyncTask if you really want to. That would definitely reduce the nice encapsulation you have now and would make it a lot harder for someone to maintain and debug down the line.
It sounds like what you have is good already, and if it's working well, why fix what's not broken.

I would assume that each ASyncTask class is an API request to the webservice, if so it is the right way of doing it. Any network operation should be done outside the UI thread.
There is also a better way of using ThreadPools to limit the number of Server requests you want to keep active at a time.

Related

Android Asynctask vs Service vs Scheduled jobs

I kinda know the pro and cons of each of these.
I'm currently developping a RSS feed list, and for that use an asynctask.
I came across a fellow android developer that advised me to use a service, because asyntask is stopped in case the app is in the background.
But then I came to realise the update of an RSS feed isn't that important, therefore why would I slow down my users by running a service ?
I know scheduled job might also help regarding the device performance but once again is it really essential to update the RSS ?
Note : The importance of the content isn't relevant. I just try to understand if I'm forgetting about some essential practice that would justify a service.
Bottom line : When it comes to a task to relative importance (such as updating RSS feed), is it worth it to run a service that might slow down the device ?
Can't we just use asynctask and admit it isn't critical if the app is put in the background ?
As far as practices go you don't seem to have any other option than using an AsyncTask or a service. But let's look at it from another perspective than the importance of the RSS feed at hand. The amount of data transferred is probably low in comparison to bandwidth available to your device. So maybe the probability of your app going to background before your AsyncTask can update the RSS feed is too small. You can also start the AsynTask in onResume(), to make sure that whenever your app comes to foreground your data is up to date, and then check for updates on RSS feed periodically while on foreground.
Sorry for long post but what I'm saying is that at the end the amount of resources you should use depends on you thoroughly studying your domain and your exact use case.

How to totally consume bandwidth?

I have an issue in my current project.
I am currently making some GET requests to a restful API (and this works perfectly). But to be more user-friendly, I would like to optimize it in order to totally consume the bandwidth.
I tried to do it with threads with an ExecutorService which receives an ArrayList of CustomRunnable etc... using this tutorial.
But it doesn't seems to work because I use a Network speed calculator app which shows peaks when I want it to be constant.
Is it possible to consume totally the bandwidth ? If yes, is my method ok?
Please ask if you need information.

Ways of making async service calls in Android? and when to use which?

If I want to make a request from an Android device to a remote service, I can use AsyncTask, AsyncTaskLoader, Intent, etc to make the a request apart from the UI thread. It seems there are a lot of options, but I am confused how to choose among them. Could you explain when and which to use? Also, are there any other options besides the ones I have mentioned?
This is an extensively discussed question, since Android provides a long list of mechanisms capable to handle service calls asynchronously, besides the one you mentioned there's also:
IntentService
Native Threads
Now, the key point in your question is "When to use it" and here would be my answer:
In software the only golden rigid rule is the "It depends rule", there's no hard rules for anything in software development there's always different ways to approach a problem in software (i guess that's the reason of the word "soft" in it...) and that's exactly why it always depends, it depends on whatever you need and although one approach might be the most common way to do it like for example "AsyncTask" it doesn't mean at all that AsyncTaks is always the way to go, it always depends on the factors and needs that affect your functionality. There's plenty of things that nowdays get executed using AsyncTaks when maybe all you need could be just a regular common Native Thread.
The only way to be able to make a decision towards the most appropiate approach would be knowing ALL the features around a tool, like for example most people 90% of the time use AsyncTaks just to run doInbackGround on separate thread, but might not even need preExecute, publishProgress, postExecute, etc, and that's something a Regular Thread could do, just like this example there's features for every single object provided in order to do remote calls, however as i already mentioned several times, it all depends on what you need and what tool fits better your needs. Remember there's no hard coded rules for "How, When, and What" to use in software, IT ALL DEPENDS, and making good decisions in that "DEPENDS" makes the difference between good developers from excellent developers...
This is a list of things i usually take on count to implement either one way or another, this list do not apply for all the scenarios but might give you an idea.
AsyncTaks- I know is a good idea to make use of asynctaks when the functionality needs to be monitored, by monitored i mean, i need to keep track of progress during my job, like (download/task progress), because that's exactly what the AsyncTask was originally created for, it was created attached to "The Task Pattern", and if i don't need to make use of at least two methods for monitoring provided by AsyncTaks like onPreExecute,onProgressUpdate, onCancelled etc. I know there might be another way to implement it.
Native Java Threads - I know is good to make use of this tool when my task is not related to any view in android at all, and do not need to be monitored (example: removing/adding data from remote database, and the response might affect just persistence elements that will not be displayed like configuration preferences)
IntentService - When i want to do a one time task in a queueprocessor fashion way, but unliked a native thread, here i would like to have some application context in order to maybe bind an activity etc...
Regards!

Android AsyncTask vs. Threads for a specific case

I am working on an application that Looks similar to the Google Play App (swipe view with gridviews inside the fragments, in addition data in the gridview [image + text] is retrieved from a remote server).
My problem is with background tasks. I can’t decide what to use for retrieval of data from the internet. Mainly I am trying to decide whether to use AsyncTask or manual threading.
Of course it would be easier to implement AsyncTask, but after some research I noticed that many people find it limiting.
In my particular case, I want to download data from the internet as Json Objects, parse them and display the data in the gridview. The gridview would have up to 30 items, each item contains a thumbnail and 3 textviews. In Android documentation, they say that AsyncTask is suitable for short operations (few seconds at most). Would filling up to 30 items be considered as a short operation?
I want the data to be fetched concurrently. Also I want to support Android phones from API 8 and above. I read that for different APIs AsyncTask behaves differently (serially or concurrently)
My question is: Is it appropriate to use AsyncTask for my app? Or do I have to do everything manually? Is ThreadPoolExecutor a 3rd way to do this? Is it easier than manual threading?
Any advice would be appreciated, I can't move forward in the implementation without deciding on this issue.
Thanks in Advance!
My understanding is that the comment about using AsyncTasks only for short operations is aimed more at not expecting the same views to be available when a long operation finishes. For example, if a user leaves the app and comes back or the current activity goes away for some reason. Typical ways around this would be to use a Service and start up a plain old Thread there, then send some message telling the current Activity to refresh when the operation is done.
The download and processing of your data is likely to be the longest operation. So I'd use that as a basis for whether this is short or long. If you don't care about persisting data at all and don't mind restarting downloads if a user leaves and comes back, you can just use an AsyncTask with very little thought.
If you are using a GridView, you should only ever be populating enough views to for just over the number displayed on the screen at one time.
I'd say that AsyncTask is fine in your situation assuming it's a few kilobytes of data and not megabytes or hundreds of kilobytes. Megs of data, I'd say move to a Service with a Thread. Hundreds of k, is a toss up.
Also, take a look into Loaders... if you want to see an alternative that is better for this kind of loading.
When attending DroidCon in London last year, a presentation brought to my attention why using AsyncTasks for loading data from the network is unreliable.
This presentation was about the RoboSpice library.
The site also has a very nice infographic explaining why exactly AsyncTasks are unreliable and what RoboSpice does to amend these problems.
Disclaimer:
I am in no way affiliated with RoboSpice, nor have I ever tried it. I was just impressed and convinced by their presentation that it's a tool worth trying.
Friend, I am working in a project exactly as you need, and to support API 8 and above you should use Asynctask to download anything or you will get a crash for API 15 and above, because it won't even let you run your app without AsyncTask even for short operations.
So as I almost did everything that you need and it is working very well for API 9 above, you should use Asynctask, I´ve implemented SherlockActionbar, EndlessAdapter and ViewPager all with AsyncTask, so go on, if you need more help just ask again later.

To download a large file, which is a better approach to use either AsyncTask or Thread?

I've found a sample to download a large data file at the following link,
http://code.google.com/p/apps-for-android/source/browse/#svn/trunk/Samples/Downloader
It seems to be pretty nice (I haven't yet tested it). But I also have read some posts at the stackoverflow to do the same thing by using the AsyncTask class, not using the Thread class as the above sample.
What I want to know is, which should I use to achieve downloading a file? And if AsyncTask is better, would you point me to a sample code?
Disclaimer: i am not Android developer, answer comes from general experience.
Thread class is most suitable for long-running activities, not for asynchronous tasks. Except if you manage pool of workers, but still lifetime of thread is same or nearly same as application. Consider that creation of thread is expensive operation.
AsyncTasks and other helpers are usually for some single activities that you want to do in background so not to block the app. They are usually well managed by the platform and are cheap.
My opinion: use AsyncTask if you want to load pages occasionally. If your app will load pages all the time in the background consider thread.
For understanding what has to be used one must understand the nature of the task we are about to perform.
Suppose we are going to download large file.... would you being a user want to see it or rather let it run in the background?? i guess i dont mind running that task in the background(unless it is game and some graphics are being downloaded).
Taking this thought in mind, if we use the Asyntask, the user must have to keep the App open until the download operation has been completed; as three out of four methods of AsyncTask runs on the UI thread. (check out the link : https://developer.android.com/reference/android/os/AsyncTask)
In the other case where we are using the AsyncTask to download graphics file for a game, it would be completely fine to go for it.
So I believe it is better to go for Thread or even better to go for Service to download the content so that one may continue to work further on the app/ close the app or even run some other app.
These two options have an equal probability of being killed while download is in progress (when user switches to another app). Still, AsyncTask is less mess. For downloading large files, consider using a Service.
AsyncTasks in Android versions prior to 3.0 uses a pool of threads in background to execute the tasks, but in versions after 3.0, a single thread is used to execute the AsyncTasks.
If you need to make a lot of requests at the same time and your Android version is higher than 3.0, use a pool of threads, but if you only have to make a single download (not mind the Android version), use AsyncTask, it will be executed at a single background thread without problems, easier than manage a Thread by your own.

Categories

Resources