I am having my UI and I am starting my Socket connection to server in another thread. Problem is, I need to wait for server reply. When it arrives, I need to do specific funcions. I have found that Handler approach can be possible, but other sites are telling this is not true. What are your suggestions? Is Handler solution right and how to do it effectively? Any example?
Thanks
Have you tried using the AsyncTask?
http://developer.android.com/reference/android/os/AsyncTask.html
Perform the network operation in the doInBackground()
Once it returns the onPostExecute() will be executed by the main thread which is able to update GUI etc.
Related
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.
I'm working on an Android app and there I have one Activity called InitActivity, where I send a request to the server in order register the user and update some data after the registration is completed.
During this action I wanted to show a ProgressDialog as a feedback to the user.
I it is possible to use AsyncTask's onPreExecute and onPostExecute to initialize and show ProgressDialog, while the AsyncHttpClient does its work in the doInBackground method but is there any better solution for this?
Thanks for any suggestions!
Yes, you definitely can do what you have just stated. An AsyncTask is used just for this purpose - to do stuff in the background. It is advisable to always try to lessen the load on the main UI thread in Android. Assuming your registration process is not intensive or time consuming, AsyncTask would be the way to go. According to Android's documentation, you should use AsyncTask for short background processes.
Just a point to note here would be that you would be making the call to display your progress dialog box in your publishProgress() method and not in postExecute() which triggers only after the doInBackground() is complete.
For my Android app I need to call a web page from activity, and wait until a response is received from remote server. So I think I need to use a new thread. Can I use AsynkTask? How can I tell to my activity that it must wait for respose to AsynkTask process?
check asyncTask
And you can use callbacks to inform the activity that the task has finished
check https://stackoverflow.com/a/13947857/1434631
Yes, you can use AsyncTask
AsyncTask has a method called onPostExecute() which lets you know when your background process, in this case, loading data from server, is completed.
Here is a nice tutorial !
I want to use AsyncTask to perform login with a server, and show a progress dialog before the connection ends.
Since there may not be response for the request, I need to set the timeout value for the AsyncTask. I found that when I simply use .execute(), the program works fine but no timeout function is implemented. When I use .get(1000, TimeUnit.MILLISECONDS), the program just halts for 1 second and no progress dialog is shown.
Any one can tell me whether the task is executed when .get(1000, TimeUnit.MILLISECONDS) is called? If yes, why there's no sign of execution; and if not, how can I implement this timeout function of the AsyncTask?
The AsyncTask.get(), if in the main thread (AKA. UI thread) will block execution.
You probably need call it in a separate thread.
Edit
Vogella made a very great article about this: AndroidPerformance: Android Threads, Handlers And AsyncTask
Take the code from here, I did and I assure you it works great without blocking the main UI thread.
I think you need to set the timeout interval on HttpUrlConnection object that would be better option to hand this situation.
If you use AndroidHttpClient it has nice preset connection timeouts.
From the documentation, the get(long timeout, TimeUnit unit) method will wait for the duration specified, then attempt to cancel the task. I think that all this will do is call cancel() on your AsyncTask, rather than performing any kind of timeout on your connection. If you are performing some kind of long download you can check isCancelled in your loop. However if you are just trying to give some kind of connection timeout then get is not the way to do it.
Please also note that get blocks the main thread until it returns. This is true of both the "timeout" version and the base version of the method. As such it is not an asynchronous operation.
To get your connection timeout, you need to perform this on the actual connection that you create, not on the task itself. There are ways of doing this for both an HttpUrlConnection and the HttpClient.
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.