canceling the current execution when the user execute new one, AsyncTask - android

I am using an AsyncTask in my application to provide the user with data when he pan or zoom the google map, I want to implement a way that cancels the current execution and execute the new request instead when the user pan/zoom so fast that he changes the location before the data is loaded, because the user will no longer need the data when he change or zoom the location on the map.
Thanks in advance

you can cancel the AsyncTask that is in execution by just calling cancel method of AsyncTask
i.e., _connectAsyncTask.cancel(true);
where _connectAsyncTask is an instance of AsyncTask.....

Related

ReExecute AsyncTask

I have several AsyncTask in my Project to grab data from some given apis.
I followed the following steps.
1) execute an Async Task and try to grab datas from there.
2) check conditions for internet and server down
3) if any issue in api or internet or server then show dialog [custom from self made class]
4) dismiss button for canceling the dialog and go back to the working stage of `app may be even by closing the activity`
My problem is I want to keep a Button "Retry" such that it shall be re executing the AsyncTask.
I searched of passing AsyncTask but it seemed worthless as I concluded AsyncTask cannot be passed. And so I am forced to repeat same code cancel(true) for various times
It would be very useful if anyone could give me solution for it with this code re-use concept.
You cannot "retry" the same AsyncTask object - you can only call AsyncTask#execute() once. However, you could create a new AsyncTask instance when the user decides to retry the download task.
Solved The problem by using a retry button that creates the new object of class implementing Async-task and executing that new object.

AsyncTask pause and resume

I have a activity that show one listview. In the activity I have a one AsyncTask (named here of AsListView) to get values from internet and fill some informations in each item of the listview. Work fine.
Now I created a button in ActionBar to show one image from streetview. To do this I have implemented another AsyncTask (named here of AsImage) to get image from google and show in a DialogFragment, but is necessary wait the execution of all AsListView Threads. It spends long time depending of the number of items in the list.
To execute AsImage rapidily, I cancel all AsListView tasks, but it's not good for me (user loss informations). The ideal soluction is set AsListView tasks to wait while AsImage execute. When AsImage finish I set AsListView tasks to continue execution. But I know that is not possible handle the control of execution of AsynkTasks.....
Some solution?
You can try to synchronize the AsyncTasks using a CountDownLatch.
Otherwise if you want you can use Threads instead of AsyncTasks and set their priorities, but there is a reason android made the AsyncTask class so I recommend you use it.

How to cancel an asyncTask and executing it multiple times?

I'm doing an app which use the new Google Maps V2, when the Map Camera moves, I need to reload the points to the new camera position, I do it with a asynctask.
The problem is when I move the camera position multiple times, app loads the points multiples times. So, I cancel the async task when the camera is moved and I don't load new point until the task is cancelled. I have an empty while loop to do it, Is there a better solution to do it?
// LOAD NEW POIS ASYNC
private void updatePoisInMap( ){
....
if (refresh_pois_async != null) {
refresh_pois_async.cancel(true);
while (!refresh_pois_async.isCancelled()) {
}
}
refresh_pois_async = new RefreshPoisAsync( ).execute( lowerLeftCorner, topRightCorner);
}
Actually, I don't think your while loop will work, or at least not as you would expect it to. The AsyncTask.isCancelled() method is normally used inside the doInBackground() method, to support early cancellation. You have several options to do what you want:
override the onCancelled() method of your AsyncTask. This is guaranteed to be called on the main thread when your doInBackground() is finished and you called cancel() on your task beforehand. In your onCancelled() you can then start a new AsyncTask. Use the isCancelled() in your Task's doInBackground() for early exit, as described above.
don't cancel the current task, but let it run. In the meantime the user may move the map multiple times. As long as a task is still running, just set a flag that it should be rerun. At task completion (override onPostExecute() in your AsyncTask) check the flag and start over if it was set.
combine the above to find the right balance between responsiveness (start loading the right POIs quick enough) and over-processing (don't start every time, but wait for the user to stop scrolling).

As location changes Restaurant list should change automatically without a button click app

I am designing an android app where I want to list all the restaurants in a particular location. This happens on the launch of the app.
As the location changes, the list of restaurants should change accordingly even if the app is already opened.
Whatever examples I got on google do this populating of restaurants on the click of a button. But in my case it happens on the launch and if app is already launched then also depending on the location the list should change itself.
I have made a MainClass under which there is a subclass of AsyncTask and this subclass has a class which implements LocationListener.
But problem is this I have to call doInBackground() method again in onLocationChange to get the results automatically when location gets changed.
Please guide me what should I do?
Put all the logic you have for obtaining the user location and gathering new restaurant data into a Service. The Service can listen for your location updates (which hopefully are set to sparse interval if you want it running all the time) and then update the list with your AsyncTask whenever a significant enough change that requires new data occurs.
You can bind to the Service in an Activity when it's in the foreground (between onPause() and onResume() methods) to get the latest information and register as a callback if the data updates during the period while the Activity is visible to invoke notifyDataSetChanged() on your list.
You can read more about creating a Service bound locally in your application here.
HTH
Use some ArrayAdapter for the restaurants list and save it's instance in the Main class, then whenever the location changed use the AsyncTask to retreive the nearby restaurants and onPostExecute replace the ArrayAdapter internal list and call notifyDataSetChanged().
Listen to location changes in your main class. Upon receiving a (significant) change start an asynctask to query the restaurants. Pass the results (e.g. array of restaurants) to onPostExecute and update your UI accordingly.
Maybe disable updates while restaurants are being queried or cancel the query and start a new one on each new update.

Android LocationManager in AsyncTask

Firstly, I know LocationManager doesn't have to be called in an AsyncTask as it's already non UI blocking :)
I have an activity which
1. Gets the users current location
2. Calls a webservice to retrieve a list of specific POIs around that location.
The user can choose to view the results as map or list using a TabActivity. Bearing this in mind the AsyncTask to get users location and call to webservice is managed by the TabActivity view rather than either of the docked views.
So I want the TabActivity to start an AsyncTask which first gets the users location, then calls the webservice. A progress dialog prevents switching views using the tabs during this process.
It's pretty much all working apart from getting the users location from the AsyncTask. The webservice code is written, the mapping and overlay code is written, the task progress dialog copes with orientation changes.
The focus on location is speed rather than accuracy. If the user chooses to view results on the mapview then I will provide a 'My location' button which will enable a more accurate location to be obtained. I just want to initially get a rough location and return the search results quickly.
Maybe I'm going about this the wrong way. Maybe I should display the map view, let the map activity find the current location, then call just the webservice in the async - but then what if the user taps the list view tab during the location phase ? I was also going to allow the user to specify their default view - some people may prefer a list to a map. In this case I would have a listview which had to retrieve the location.
Thanks for any advice
Martin.
I sussed it.
The problem I was having was that the LocationListener was not being called in the AsyncTask.
The reason for this was that although I'd created and prepared a lopper in the thread I hadn't called Looper.Loop()
I start the requestLocationUpdates, kick off a timer. Either the locationmanager responds with a location, or the timer expires. At this point I call looper.quit() to ensure things return to normal.
Seems to be working. You also have to remember to respond to the back button etc, cancelling the timer and looper if the AsyncTask is cancelled.

Categories

Resources