As all requests in Volley are executed asynchronously on a different thread without blocking the “main thread”, is there any way to wait for the request to complete and then continue the main thread execution?
You should design your app such that it keeps the main thread live at all times. You can then have blocks of code run when the response has been received using listeners or async task. Check out my answer using listeners here. Or look at onPostExecute for AsyncTask.
is there any way to wait for the request to complete and then continue
the main thread execution?
An alternative is to show a loading dialog box while volley is working. This way you can prevent the user from interacting with your app until the request is completed (just don't forget to give him a chance to cancel).
Volley is meant to work in parallel with your main thread and tell you when the request has completed (what all apps should do) if you don't desire that, don't use Volley. But you'll get a NetworkOnMainThreadException and if you manage to bypass it, you'll end up with an ANR exception.
Related
I am working on JOB queue. Here the scenario is i am storing 3 api calls in job queue. The first API is having more information in json. but last two is having less information. According to the priority when network is available it is calling those apis one bye one in right order. but as the first api is having more information it is taking more time to hit the server so it is reaching the server at last. Is there any way where after hitting the server we can able to run the rest APIs?
To manage your network request one after other you can Use AsyncTask.
AsyncTask have 3 main method i.e
1)onPreExecute - can perform any Ui update while calling network request.
2)doInBackground - which run in background thread not on main thread.
3)onPostExecute - after doinbackground process onPostExecute will call.
like this you can call your request when first request get completed ,So on first onPostExecute , call second request and so On.
I hope like this you can manage your network request in serial way. Thanks :)
I was wondering is it ok to execute a Thread inside the doInBackground method of Asynctask. Should I avoid using this kind of structure on my codes? And if yes, why should I avoid it? Would this cause any ineffectiveness in my apps?
In principle, there's no problem with starting a thread in the doInBackground() of an AsyncTask, but sometimes you see this done not because it's the right thing to do, but because of a misunderstanding about how AsyncTask works.
The point is that doInBackground() will automatically get executed on a background (non-GUI) thread, without you needing to create a thread for it yourself. That, in fact, is the whole point of an AsyncTask. So if you have a simple, linear task that you want executed in the background, you do it with an AsyncTask, and you don't need to do any manual thread creation.
Where you might want to start a new thread in an AsyncTask is if you want your background task to use multiple threads to complete. Suppose that you were writing an app to check the online status of various servers, and display something about their status on the screen. You'd use an AsyncTask to do the network access in the background; but if you did it in a naive way, you'd end up with the servers being pinged one by one, which would be rather slow (especially if one was down, and you needed to wait for a timeout). The better option would be to make sure that each server was dealt with on its own background thread. You'd then have a few options, each of which would be defensible:
Have a separate AsyncTask for each server.
Create a thread for each server inside the doInBackground() of your single AsyncTask, and then make sure that doInBackground() doesn't complete until all the individual threads have completed (use Thread.join()).
Use a ThreadPool / some kind of ExecutorService / a fork/join structure inside your single AsyncTask, to manage the threads for you.
I would say that with modern libraries there is rarely a need for manual thread creation. Library functions will manage all of this for you, and take some of the tedium out of it, and make it less error-prone. The third option above is functionally equivalent to the second, but just uses more of the high-level machinery that you've been given, rather than going DIY with your thread creation.
I'm not saying that threads should never be created manually, but whenever you're tempted to create one, it's well worth asking whether there's a high-level option that will do it for you more easily and more safely.
is it ok to execute a Thread inside the doInBackground method of
Asynctask.
yes it is but it really depends on your application and your usage. for example in a multithread server-client app you must create for each incoming clients one thread and also you must listen on another thread. so creating thread inside another is ok. and you can use asynctask for listening to your clients.
Should I avoid using this kind of structure on my codes? And if yes,
why should I avoid it?
If you design it carefully you do not need to avoid, for example make sure that on rotation you do not create another asynctask because for example if your user rotates 5 times you create 5 asynctasks and in each of them you create a thread that means you will get 10 threads, soon you will get memory leak.
Would this cause any ineffectiveness in my apps? Can you explain
these questions please.
I answered it above, I think better idea is using Thread Pool to minimize number of creating your threads or wraping your asynctask in a UI less fragment so you are sure you have one asynctask regardless of whats going to happen.
In any higher programming language, there is concept of multi-tasking. Basically the user needs to run some portion of code without user interaction. A thread is generally developed for that. But in Android, multi-tasking can be done by any of the three methods Thread and AsyncTask.
Thread
A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its run() method.
The other is providing a new Thread instance with a Runnable object during its creation.
A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.
If you use Java threads then you need to handle the following requirements in your own code:
Synchronization with the main thread if you post back results to the user interface
No default for canceling the thread
No default thread pooling
No default for handling configuration changes in Android
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
1. onPreExecute()
Invoked on the UI thread before the task is executed
2. doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
3. onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
4. onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html http://www.mergeconflict.net/2012/05/java-threads-vs-android-asynctask-which.html
I would say there is no problem in doing that if you need something to run concurrently beside the AsyncTask.
One issue could be one of readability (using 2 different ways for concurrency), but I really can't see the harm in that - especially if one of the tasks needs to show it's result in the UI and the other one doesn't.
I have finished to write webservice in android. But if there is no service or connection or network problem, webservice is searching for that. It takes time. How will handle webservice calling in slow response from webservice?
Can any one assist me to handle this issue?
You need to call the webservice from either a service (docs here) or an AsyncTask (docs here). If you're going to be interacting with the webservice for a while, then I would use the former. Otherwise, I would use an AsyncTask. The main thing to remember is make sure that you do NOT make this call on the main thread or your application will most likely block and Android will display an ANR dialog.
Also, note that, if you use a service, you need to start a new thread and launch the service from that thread to help prevent the application from blocking.
There's a tutorial here that might be helpful.
Hope this helps!
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.