One difference between handler and AsyncTask in Android - android

Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?

Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.

Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.

Related

Asynchronously load data in android

what is meant by asynchronously loading data in activity or fragment in android?
This is my question. I searched everywhere. I'm not getting a generalized definition for this?. I can't get the term mentioned in android developer also.
Can anyone provide me the basic explanation of this term?
Asynchronous in Android mean that you do stuff while the user can interact with the User Interface (UI) : you are not blocking the UI while you are doing long stuff. So the user can still navigate, change activities or fragment and your data is still loading.
For data : you load it, parse it and do whatever you want in a NON-UI Thread (using AsyncTask eg) and then notify the UI, and display what you need to.
You have many possibilities to implement Asynchronous load in Android, and you have many different way to manage your request. I personnaly recommend using Retrofit if you need to use a Web API.
It means that you load your data in a separate thread than the UI thread. You launch your HTTP request for example in another thread and when it finished you notify the UI thread to refresh display.
This mean to load data in separate thread rather than load the data in main thread.Loading data in main thread may cause app to block
The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask .
An AsyncTask is started via the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

Is there a callBack to SetContentView in Android?

Is there any callBack to setContentView in Android, since i'm doing a heavy operation right after setContentView line, and it seems to skip that setContentView.
So i was thinking of moving the heavyOperation to the callBack of setContentView.
Thanks
EDIT:
Pseudo Code:
AudioRecord Finishes
SetContentView(1) //To show a "Processing" screen with no buttons
FFT analysis
SetContentView(2) //On FFT analysis DONE.
In my case "SetContentView(1)" NEVER occurs.
EDIT # 2:
I did the heavy operation in another Thread, and used Handler to send a Message after heavy operation finishes to treat it as a callBack.
Thanks for all the help guys
Short answer: No callback for the setContentView.
If you are doing network operation then you can use the AsyncTask for this.
If you are doing any more heavy operation and want to update the UI then you can do that using the Service and BroadCastReceiver.
For this you have to make your own callback using the interface.
heavy work should be done in asynk tasks or as a service or on other threads
Don't do any heavy calculations on the main UI thread where onCreate() and such are run.
What happens that the first setContentView() posts a "layout and draw" message to the UI thread message queue. Then your calculation blocks the UI thread, preventing messages in the queue from being processed. The second setContentView() posts another message to the queue. When the control eventually returns to the message loop, both messages are processed and you'll get the layout set up by the last call to setContentView().
For heavy computations, use a separate thread. For example, an IntentService or an AsyncTask make threading easier.
My hack.
final Handler handler = new Handler();
setContentView(layoutResID); // This posts some messages to message queue.
handler.post(new Runnable() { // Post another message at the end.
#Override
public void run()
{
// Called after layout has changed.
// If you want to skip some more works (like transitions),
// call another handler.post() here.
}
});
To see what happens, set a break point at the line Message msg = queue.next(); in Looper.loop() may help.
I was facing a quite similar problem a day ago, but I figured it out. (I know your problem is solved, just offering a different approach which doesn't require a handler or callback.
Most Suitable for running U.I. functions :
If you need to do something like this :runTask() then
setContentView() (or any other ui function) you can run the task on different thread by using AsyncTask or you can set a timer for when the task is completed (if your task takes a certain time), the User Interface functions will be called.
But since the Timer class, runs the functions on a different thread, you can not run the setContentView() inside it. So you can use a runOnUiThread(Runnable action) method inside the overloaded run() function of Timer class. You just need to define a function that returns a runnable. Define your Ui operations in the runnable action.
Hope it helps someone.

android async task usage in depending sequence of tasks

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(...).

Use ASyncTask onProgressUpdate to update UI

I have an ASyncTask that tries to
find an image on disk
checks if newer online
Then in onPostExecute update the image
I would like to update image (i.e. sync to ui thread) both after checking disk (which is fast, but still to slow to do in e.g. ListView getView) and after checking online.
If I read the help correctly, I can call onProgressUpdate (executed in UI thread) by using publishProgress(Progress...) ... However, can I be sure of the order? I don't care about timing (if I have to wait a little) but I would like to make sure "disk-progress-state" happens before "online-progress-state"
It's entirely up to you to decide when you call publishProgress() and what parameters you pass to it.
If you want to call it twice from your background thread - once after the disk check, and once after network check - then that's fine. To distinguish between the two calls in your onProgressUpdate() just keep track of what state you're in or keep a count of how many times that function has already been called.
The calls on the UI thread will be in the same order as the calls you make to publishProgress() in the background thread.
If I understood you correctly you are asking if executing publishProgress invokes onProgressUpdate in the same sequence. The answer is yes, because it is posting messages via handler to the UI thread.
Here is the code from AsyncTask publishProgress
sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget();
AsyncTask runs the methods on the UI Thread by sending Runnables to the main thread Handler. This Handler takes every Runnable in the FIFO queue and run them after another sequentially with no parallelism. Thus if the disk-progress-state happens before online-progress-state, then the order of the publishProgress's is preserved.
The same applies to the order of publishProgress and onPostExecute.

AsyncTask - How to wait for onPostExecute() to complete before using values it has updated

I have an API in one jar that uses AsyncTask to carry out some work in the background. I need to wait for the result to be returned and then do some more wok with this result.
I signal back to one class in onPostExecute() method and then the result is handled on the UI thread, but the handler needs to be defined as a callback in a different project altogether so I can't just do the work in the onPostExecute.
In the second project I need to wait for the AsyncTask to end AND for the response to be handled, then I need to display the results of the handler to a TextView in an activity in the second project.
Thread.sleep and using a CountDownLatch don't work because the handling is done in the UI thread. Is there any way to do such a thing?
If I understand correctly, you have AsyncTask in one jar and UI that needs to be updated in another jar. If you run them as one application it should not matter where they are located. Since you mentioned that some callback is involved you can just execute this callback in onPostExecute.
The following will be an approximate sequence of events
Activity from jar 2 creates async task and passes callback that knows how to update TextView as parameter to constructor
AsyncTask stores callback in instance variable
Activity executes AsyncTask
AsyncTask in onPostExecute calls method on callback with appropriate parameters
Callback updates TextView

Categories

Resources