My Boss told me Not to use AsyncTask<> to hit a webservice. Standard told me use Threads to hit a webservice and then use the Handler to process the response from Thread. Can someone ellobrate how to use thread and handler to hit a API and then give the control back to the Handler , atleast a Tutorial if its possible or Code. What is handler, is there only one Handler in android Application? thnks
Please check it below example:
http://androidexample.com/Thread_With_Handlers_-_Android_Example/index.php?view=article_discription&aid=58
What you are actually trying to do with Thread and update your GUI with Handler is same as using AsyncTask. AsyncTask considers most of the aspects which are somehow difficult to manage. Obviously there are some downsides to use AsyncTask for more details have a look at my answer Down sides of AsyncTask
When to use?
If you're supposed to perform a short time request, then AsyncTask is perfect. However, if you need to get some data and display it but you don't want to worry about whether to download again if the screen is rotated and so on, you should consider using an AsyncTaskLoader.
If you need to download some big data, then you can consider using an IntentService.
Related
Hi guys I have a question about Asyntask which is used in android studio :
As far as I know AynTask is used for user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished.
But let's say that I want to register an account so that I can login, that shouldnt take time at all so why should I use Asyntask for this?
Let's say I want to send 100 strings to the Database, that can be done in milisecs I think, so again, why to use and how to decide when to use Asyntask?
I hope you guys can help me out, I have been searching for a long time !
If you don't know how much time operation will take, you should perform it in a separate thread and then pass the results to UI thread. I think the database should be accessed in a separate thread as well as HTTP requests. In the case of time-consuming query, it may be a long operation. AsyncTask is one way to do it. You can also use other techniques. The popular technique used nowadays is applying RxJava library, which gives you the high-level functional reactive interface for writing multi-threaded applications with a few additional features. You can perform an operation in e.g. Sechdulers.io() (I/O) thread and then pass the result to AndroidSchedulers.mainThread(), which is UI thread.
There are also other techniques like using Looper & Handler from Android SDK or using Thread class from Java, but such techniques require more knowledge, more work, writing more boilerplate code & you have more problems to deal with.
I'm trying to make a web app using the WebView component. I need to modify the HTML before I show it to the user, so I tried to download it, modify it and the load it. I did this using the HTTP response and get classes and because of a series of exception I had to put them in an AsyncTask. Now the problem is that this solution works but it has a short delay because I have to wait for the Thread to end and then I can call the WebView.load() method either for the home and the other links. It is really ugly...do you have any solution to suggest me? Something without Async Tasks maybe?
The Android documentation states, that you should NEVER perform network operations on the main thread (otherwise, it will give you an exception).
Waiting for the AsyncTask to complete its background workflow is a natural process similar to think over the problem before giving the solution (your brain need to compute it in the background, if you will).
You will wait in any case. The server can't provide information instantly. But if you make request not in AsyncTask, it will block your application. And then android will offer to stop it. You dont need it. Instead of this you need to show something like process dialog.
There are a couple ways of getting data Asynchronously in your app. One is a Handler and another one is an AsyncTask. Now I've used both, and would like to know which one performs better/more efficiently at some tasks.
Thusfar, I've mostly used AsyncTasks in getting Webdata, and Handler's in getting data from Services to Activities.
I would like to know if there is an advantage to using Handler's for Webdata, or using AsyncTasks for refreshing UI from Services. What is the big difference?
Since AsyncTask uses a Handler, your comparison is... odd.
AsyncTask is great for transactional work: stuff that will take more than a few milliseconds and less than a few minutes. For that sort of work, if you have no need for your own thread management, AsyncTask is generally simpler to use.
If you have some particular characteristics that you need for your threading that AsyncTask will not readily handle, or if you need the thread for an indeterminate period of time (e.g., until the user presses a Stop button), use your own thread and something else to get work to the main application thread: a Handler, or post(), or runOnUiThread(). The "indeterminate period of time" recommendation assumes you are using one of the built-in thread pools -- I am never a fan of tying up a thread out of a thread pool that you didn't set up.
Looks like AsyncTask uses its own internal Handler. My testing is the "post" using a Handler is enqueued immediately. When used in onCreate this can be problematic as other actions must be enqueued after onCreate (haven't read through Android Activity etc source on this yet). So, trying to post to later load the layout did not work. Had to use an AsyncTask. Since AsyncTask has its own internal Handler; perhaps, then creating the task might occur in the queue directly after onCreate but the doInBackground and onPostExecute might occur later as they are later in a queue.
So, AsyncTask worked better for this UI need to load an overly large layout file later with setContentView - later meaning after the onCreate so a ProgressDialog could be shown. ProgressDialog doesn't show up until onCreate is done.
Also, see this article for how to choose when to use AsyncTask. Basically says when wanting to update UI. But actually you can do this with runOnUIThread so don't really need handler nor AsyncTask if you already know Java threading. runOnUIThread is like the invoke/invokeLater stuff in Swing.
I am new to android development. Currently i am working on an application which will take a query from user, send the query to the server and will receive an XML response in return. Then it will process the xML response using XMLparser, will extract the answer from XML response and display answer to the user. Since all this processing takes some time, i want to show a progress dialog to the user for the processing time it takes.
I have gone through some ways of doing this like i can use AsyncTask, Handler or Runnable (java) threads. But as much I have read about all these, I have got confused which one to use.
Please tell me which one is better to use for above mentioned scenario. And a simple way to implement the preferred one.
Thank You in advance.
I'd recommend you to use AsyncTask because it is simplier than other approaches and it suits your needs.
I think you mess a bit these three different entities:
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler is a special class that can handle messages that are sent to the handler's thread.
From http://developer.android.com/reference/android/os/AsyncTask.html :
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed for a use very similar to yours.
Runnable is only to run a block of code on another thread:
Represents a command that can be executed. Often used to run code in a different Thread.
(http://developer.android.com/reference/java/lang/Runnable.html)
Handler is used more for Message Queuing. Your case doesn't seem to require messages being sent repeatedly.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
http://developer.android.com/reference/android/os/Handler.html
Note that neither Runnable nor Handler talk about displaying the results back on the UI thread. That is where AsyncTask helps you more than either of these.
It may be my personal preference - but I would use AsyncTask in your case. It provides all necessary controls for starting up the task, updating progress as necessary, etc. I have a very similar requirement in my app (send request to server, get response in XML, parse response, do something with the data) - I'm using AsyncTasks for this purpose.
As far I know AsyncTask is the recommended way. I think is the easiest way to implement and the more "Android best practice" for asynchronous tasks.
Could you refer to this question
Here's how I see it.
Handler is more for queuing many actions, and gives a bit more control. It's better for repetitive tasks which are generally not restricted to the UI.
AsyncTask provides a simple way to do background processing, not caring much about the lower-level stuff. It's great for relatively small, individual UI updates.
IMO, you should use AsyncTask. That being said, it's kind of a toss-up.
I think it's a matter of self-preference, but in your case I would go for the AsyncTask because it facilitates the interaction between the UI thread and the background thread.
I'd use a combination of AsyncTask and Handler, because please remember that you cannot change the UI from outside the UI thread (in this case you cannot intervene and show the answer to the user).
To overcome this, I ran the AsyncTask and catched the result with a custom callback method, which simply encapsulate it inside a Message and sends it to my custom Handler, which is inside the UI thread and can safely render on-screen my result.
AsyncTask might be the choice,because it provides all necessary controls for starting up the async task, updating progress bar, etc.
But, the point is AsyncTask is the best solution to the scenario.
Handler or Runnable are more suitable to duplex cases, like chat apps.
Can anyone give me a clear description of what is AsyncCallBack? Does it exist in the latest android version? Because I am directed to AsyncTask when I search for AsyncCallBack.... Are these both same? Does anyone have an example?
Thanks in advance.
There is no class named AsyncCallback in android. I think what you are looking for is AsyncTask which is a way to run a piece of code on another Thread so the UI won't be blocked, and receive it's results on the UI thread. For example, say you want to talk to a server on the internet in response to the user clicking something in the UI, then receive some result from the server, and update the UI. AsyncTask makes doing this very easy compared to doing regular threading code because threading lifecycle and communication back to the UI thread is handled for you. As a bonus there is also support for canceling a background task, but you have to write the code to handle it when cancel is called. It doesn't do it without some work on your side.
I think the terms may be mixed up here, there isn't an AsyncCallback in Android (as far as I know). There is however very widely used AsyncCallback interface in GWT (Google Web Toolkit): http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/rpc/AsyncCallback.html.
In Android you use AsyncTask to easily run background operations asynchronously on a separate Thread from the main UI/app thread: http://developer.android.com/reference/android/os/AsyncTask.html.
Here is a good intro article on AsyncTask: http://developer.android.com/resources/articles/painless-threading.html.