Just wondering if there is a possible way to update the data of AsyncTask's doInBackground. Like for example rotating an image, I use bitmap which I want to update each time the UI thread gets a new data, I want to pass that data to AsyncTask which it can work in the background.
Any tips for that? Thanks
AsyncTask is meant to do a small amount of work and exit. They are not meant for long running operations, so it wouldn't be appropriate to try to pass new data into it.
It sounds like what you should do is:
UI gets a new image
Start a new async task to process the image. Store task in member variable.
If UI gets a new image again, check if existing async task is still running. Either cancel that task and start a new one, or discard the new image and let the current task run to completion.
Related
My App contains a function that takes time to load ( parsing files).
THe function is called at multiple user case, i.e. from multiple user triggered condition.
Besides, it is called when onCreate is called.
In simple word, the flow is:
User click/OnCreate trigger
Function to parse file
Post to windows
Other postprocessing
I hope the user can click cancel to stop parsing files.
I tried to use asynctask. I know I can put the function to onPostExecute.
But I assume onPostExecute is just for dismiss progress dialog. Or I have to move a lot of codes ( for different cases) to it. Not a good idea.
I do not suppose user to do anything during parsing files.
So, what is the best way to do so? Despite I know it is not good, I think i have to occupy the UI thread.
In simple word, I want to wait for "parsing files", but i do not want to occupy the UI thread, so user can click cancel.
update:
I tried. however, there is a problem:
I use asynctask. I called:
mTask = new YourAsyncTask().execute();
YourAsyncTask.get(); // this force to wait for YourAsyncTask to return.
DoSomethingBaseOnAsyncTaskResult();
YourAsyncTask.get() hold the UI thread. So, there is not loading dialog, and user cannot click cancel from the dialog. It seems I have to move every line after
mTask = new YourAsyncTask().execute();
to
OnPostExecute()
which i did not prefer to do so because DoSomethingBaseOnAsyncTaskResult() can be very different based on the return result. or else, it becomes do everything in YourAsyncTask()
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time.This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
CODING
To start an Async task
mTask = new YourAsyncTask().execute();
and to cancel that task
mTask.cancel(true);
More detail is available here
In order to use the AsyncTask API, one has to follow the steps described below:
Create a class which extends AsyncTask.
Fill in the generic types available as generics in the class for:
the task execution array parameters
progress array parameters
result array parameters
Implement the method doInBackground(Parameters... parameters). This
method must execute the job which is supposed to be quite demanding.
Optionally, one can implement methods for:
cancelling the task - onCancelled(...)
executing tasks before the demanding task - onPreExecute(...)
reporting progress - onProgressUpdate(...)
executing activities after the demanding task is finished
-onPostExecute(...).
For the down voters,it would be better if you could provide a working solution,not every question need to have a code attached with it,if one is not clear with the concepts how can u expect him to provide you with the code he played with??
This is basically a conceptual question,i tried reading docs but still i couldn't get a better understanding of the topic. i am not sure how i should use async task....
i have used the async task before for displaying an image from internet,
but i am still confused how it works.I know 3 of its functions that are used commonly.
i.e
1.onPreExecute ()
2.doinBackground()
3.onPostExecute()
now i am confused that if i have to populate a list how should it be done??
I know The populating part should be done in the doinbackground(),but after that should i return the result (from the background),after the whole list has been populated, to
onPostExecute() and expect that the list will be loaded on the listview asynchronously
or should i return the result in parts(say a new item has been added to the list,send it to the onpostexecute immediately without waiting for the whole list to be generated, to be displayed and repeat the iteration ) to the onpostExecute()??and manage the lazy load ourselves by doing so?
well.. why don't you see this below android API information..
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
onPreExecute() method is used when starting asynktask function.. typically in this method, someone use progress dialog..
and doInBackground() methos is used when progress dialog is running. in this method you can implement your job(function) that you want. I think this part is the most important point among methods of this asynktask class
and onPostExecute() method is typically used when finished background job.. in order to deliver some kind of data or result.. to View
I have a file downloading android application.Here file is downloaded when user click on listview items.It works fine.
Now,I want to cancel current file download and start next file while user taps on other items and another download is already progressing and show user confirmation before canceling the download task.
How can i do this?
Thanks in Advance
First, you must check in your AsyncTask
// in doInBackground, check if asynctask is canceled manually
if (isCancelled()) break;
In your activiy, whenever you try to cancel, just cancel AsyncTask manually, and of course, start a new one to download another file!
mDownloadingTask.cancel(true);
Simply , you store your Asynctask to a variable:
mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();
When you want to stop this task and start new one:
//close the current task if it # null
mDownloadingTask.cancel(true);
mDownloadingTask = null;
//Start new one
mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();
Cancel(false) sets a flag, which you can check in doInBackGround() and stop your code from doing what its doing. cancel(true) does the same except it also interrupts the thread. See more info about interrupts here.
This is all good when you have a looped code in your task. Every iteration of the loop, you can check isCancelled().
But as in your question, some tasks like downloading a file do not use loops, perhaps you are just calling an external API method, so here, you are on the mercy of this blocking method. If well designed, it will throw an exception when interrupted, and the thread will terminate.
Also, have a look at a better implementation, SafeAsyncTask
Once an AsyncTask call is finished is the thread deleted?
I stored an AsyncTask in a var "guiThread = (GUIAsyncTask) new GUIAsyncTask()".
The first call to execute() works but subsequent calls don't.
So, do I just create new tasks whenever I need them? I was under the impression that I used my variable over and over and calling new over and over would spin up thousands/millions of threads.
AsyncTasks are one-time uses. They start, execute, then die. Then you have a choice of keeping the reference around to gather information from it that may be stored in the class post-execute, or dumping the reference and letting the garbage collector handle it. If you want to start the AsyncTask again, you have to create a new object and start it.
Nope you need to create a new AyncTask everytime you want to use it.
An AsyncTask must be created any time it is to be used
We have to use Asynchronous Task to start our new Activity on Tab Click event but in the ListView or any view we can directly can start the new activity Why?
http://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask enables proper and easy use
of the UI thread. This class allows to
perform background operations and
publish 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.on the UI thread.
Basically you want to avoid that the loading process/device hangs when loading loads of data to the list initially, that's why you make it async, outside the UI thread, so the user can use the app while data is loading in the background.
Starting an activity is faster than loading lots of initial data into a long list view, especially if it's remote data from a remote server. Therefore the app you're looking at is probably using this here.
If you want to perform some task in background at the same time you want to do another task at the forground.
http://developer.android.com/reference/android/os/AsyncTask.html
This link surely will help you.
You just try this one will help you.
http://xoriant.com/blog/mobile-application-development/android-async-task.html