Use ASyncTask onProgressUpdate to update UI - android

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.

Related

Thread.Sleep issue android methods and asynctask

I am working on app that updates data for every 8 secs and the update was done using Async task. I am using loops to achieve this condition
while(const_val > update_val) {
new Asynctask().execute();
Thread.sleep(8000);
}
const_val will be constant and will be not be changed by any other methods.lets say this value will be 5.update_val will be updated and decremented when Asynctask is called and let's the value will be 10. So , the while loop executes until the condition is true and asynctask ,sleep are called .
When I use above while loop in a general method then UI gets locked and if I use the same loop in another asynctask there was an error saying "Only original thread that created a view hierarchy can touch its view "
You need to change your code to start the AsyncTask and have it provide an update via its onPostExecute() method. By calling Thread.sleep() you are sleeping the main thread (or UI thread) of your app, which is not good. You do not ever want to block the main thread. This article may help you better understand AsyncTask and threading in Android: http://po.st/Cei3m2
I don't think you should use a surrounding loop. Look at this example:
http://javatechig.com/android/progress-notification-in-android-example
the AsyncTask is a private inner class
the onPostExecute updates the UI with a message/cancels the load bar
This way you don't have to loop and the onCreate() can return instantly.

Can a background thread trigger a message handler on UI thread in android

I have a thread which is started in onCreate() and this thread fetches some data.
Is it possible that before the thread is terminated should be able to update the ListView?
Now as the thread is not the UI thread, it cannot directly update the listview array adapter.
Is there a way out?
I was thinking that is it possible to trigger a Handler from thread whose runnable gets executed on main UI thread.
Not sure if I understood your problem completely, but I believe there are two ways to achieve what you want:
1- Start an AsyncTask instead of a thread. AsyncTask's onPostExecute() will run in the UI thread, which means you can do anything UI-related in there. You can start the AsyncTask in onCreate(), and, once it finished, it calls a method on your activity which does:
myAdapter.notifyDataSetChanged();
2- Use runOnUIThread()
Use your Activity's runOnUiThread(Runnable action)
link

One difference between handler and AsyncTask in 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.

Does posting a Runnable with a Handler make things asynchronous?

I am updating an activity's UI from a BroadcastReceiver that I register in the same activity. The API docs say:
[...] The function [onReceive()] is normally called within the main thread
of its process [...]
so I suppose updating the UI is okay.
The docs also say:
[...] you should never perform long-running operations in it (there is
a timeout of 10 seconds [...]
I am just setting some text on a TextView so I suppose that won't ever take longer than 10 seconds.
But, and here comes finally my actual question: Does it make any sense at all to add a Runnable to the main thread's message queue using a Handler, so that onReceive() can return immediately and the UI update happens at some later point in time, as the docs suggest:
There are two main uses for a Handler: (1) to schedule messages and
runnables to be executed as some point in the future; [...]
?
If you're just setting text on TextViews then you won't have issues. No need to over-complicate things with Handlers.
Though I will say that some people like using handlers just because it keeps things organized if multiple calls to a specific UI method need to be called. Using a handler will guarantee that that executed code will be initially placed on the UI thread, so it avoids having to check which thread you are running on.
The important thing to keep in mind is that all UI actions should be performed on the UI thread, and any sort of intensive processing should be done on a background thread.
Yes, using a Handler to schedule a Runnable is the standard.

What is the Android UiThread (UI thread)

Can someone explain to me what exactly the UI thread is?
On developer.android.com it says about the runOnUiThread function
public final void runOnUiThread (Runnable action)
Since: API Level 1 Runs the specified action on the UI thread. If the
current thread is the UI thread, then the action is executed
immediately. If the current thread is not the UI thread, the action is
posted to the event queue of the UI thread.
Does the UI thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc.? If not, what exactly does the UI thread include ?
Thank you
The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.
For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.
For more info on your application's Processes and Threads click here.
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.
For more info on spawning worker threads and updating the UI from them click here
I personally only use the runOnUiThread method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.
For more info on testing and running code on the UIThread click here
If you execute blocking code (e.g. a Http-Request) in a separate Thread, consider using AsyncTask. Its doInBackground-Method runs on a separate Thread. AsyncTask provides you with methods onProgressUpdate and onPostExecute which are guaranteed to run on the UI thread.
If you need GUI-progress updates (e.g. via a progressbar) call publishProgress inside doInBackground. This leads to a subsequent call of onPublishProgress which is also guaranteed to run on the UI thread.
onPostExecute is automatically called after doInBackground returns.
All UI drawings etc. happen in a separate thread. Its called the UIThread. If you want to make any change to UI u must use make sure it happens in UIThread's context.
Easiest way of doing it is to make use of runOnUiThread

Categories

Resources