Using Variables on UI Thread from Worker Thread - android

The Android Developers site states that two rules must be followed when working in the UI thread, i.e.,
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread*
Does this mean that I can access variables in the UI thread from within a worker thread, i.e., not UI toolkit?
If so, do any special considerations need to be given if the variable is being continually updated, e.g., from a SensorEventListener. Thanks.

Does this mean that I can access variables in the UI thread from within a worker thread, i.e., not UI toolkit?
Yes, as long as they are declared as member variables then you can access them. You can even access values in UI elements such as using getText() on a TextView you just can't update any of the UI elements.
do any special considerations need to be given if the variable is being continually updated,
If they are being updated then you may want to have a way of syncing the variables. A good way to do this would be to use an AsyncTask and update the variable in onPostExecute().
If you aren't familiar with using AsyncTask, make sure you look through the Docs several times and understand them.

No, you can't access them outside the UI thread. Very few UI elements can be accessed from a non-UI thread with one being ProgressBar.

You can access UI elements in a separate thread but you cannot update them
The only way you can update a UI element in a non-UI thread would be to have a callback to the UI thread in the separate thread using runOnUiThread or using a Handler aside from that you cannot make changes to a UI element in a separate thread

Variables are not to be accessed outside the UiThread. If you'd like to make modifications from outside the UiThread use :
Activity.runOnUiThread(Runnable)
Some "post" method that stores modifications waiting for the UiThread to treat them. You can use a BlockingQueue for example. Have a look at java.util.concurrent package
In some very rare cases the modification of a variable outside the UiThread cannot produce errors in which case it is safe to access it out of the UiThread. In other cases variables should be private, and attempts to access them outside the UiThread should raise IllegalStateException or something like that.

Related

How to tell if code needs to be run on the UI thread

I'm using a worker thread in my app so it's vital for me to know which code can be run from the worker thread and which code needs to be run on the UI thread.
In the Android documentation, the following hints can be found:
So, you must not manipulate your UI from a worker thread—you must do
all manipulation to your user interface from the UI thread. [...]
However, note that you cannot update the UI from any thread other than
the UI thread or the "main" thread.
(source)
But what "manipulation to your user interface" means in practice is often not as clear as it seems. Of course, it's clear that you cannot hide views, manipulate button texts, add list view entries, etc. from a worker thread.
But what about calling setRequestedOrientation() from a worker thread, for example? Is that allowed or does it fall under UI manipulation and thus must be called from the UI thread? Is there any way to tell or should I stay safe and better run the code on the UI thread when in doubt?
In general you should take guidance from the API documentation. For example the Activity.onCreate() explicitly states that:
This method must be called from the main thread of your app.
For the example you gave Activity.setRequestedOrientation() there is no explicit statement that the method should be called on a particular thread. Usually if threading is of concern the documentation will state that.
If you would prefer certainty then you called also call upon Activity.runOnUiThread()

Executing a Thread in Asynctask and its complications

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.

Accessing Android UI toolkit from worker thread

According to Android doc,
"...Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread"
That seems very plausible, but is it correct that the compiler does NOT complain at all if a programmer violates the second rule?
You will not get a compile-time error. You may (or may not) get a run-time error.
There are many ways to update UI like
Handler
AsyncTask
runOnUiThread method of View
BroascastReceiver

Understanding when and why to use different Android threads

Hopefully someone can explain this to me or point me to a resource I can read to learn more. I am building an app that uses a ListView and a custom list adapter that I modeled off one of the many tutorials available online such as this one:
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
It worked fine. However, every example of how to do this runs the process of building the list of objects to be displayed and collecting the required data on separate threads.
I want to know why/couldn't you just put everything into onCreate? I can't see a reason why you would need separate threads to make this happen. Is there some general form/standard for when/what must me run on certain threads?
The Android docs on this are very good, as with most things.
The upshot is: the UI should always be responsive. So if you have some operation that will take enough time that the user will notice, you might want to consider not running it in the UI thread. Some common examples are network IO and database accesses. It's something of a case-by-case basis though, so you have to make the call for yourself a bit.
Well, if building the list of objects is not a relatively short process, doing it in onCreate() would be blocking/slowing the main thread. If you use a separate thread, it will allow the android os to load all of the UI elements while you are waiting for the list to be populated. Then when the list of objects is ready, you can instantly populate the already initialized UI, as opposed to waiting to initialize the UI until after the list of objects is built. It ensures that your application will always be responsive for the user.
Because you only have 0.5 sec to execute onCreate — after which the dreaded ADN (application not responding) error message is displayed. So unless your list view is super simple you won't make it it in time. And even if your list view is super simple it is better to learn it the proper way.
BTW: I don't even use threads, I use one or more Services to do all the work. Even more difficult to implement but more robust and responsive as well.
The reason you don't do things in onCreate or on the UI thread is for responsiveness. If your app takes too long to process, the user gets shown an App Not Responding dialog.
my teacher once said: every software can be written in a single (big) for loop.
And if you think: it can be... maybe at NDK level.
Some SDK developers wanted to make the software developers tasks easier and that's, why exists the SDK's and frameworks.
Unless you don't need anything from multitasking you should use single threading.
Sometimes there are time limitations, sometimes UI/background/networking limitations and need to do stuff in diff threads.
If you see source code of Asyntask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).
Why does it mean ? It means no magic in Asyntask or Handler. They just make your job easier as a developer.
For example: If ProgramA calls methodA(), methodA() would run in a different thread with ProgramA.You can easily test by:
Thread t = Thread.currentThread();
int id = t.getId();
And why you should use new thread ? You can google for it. Many many reasons.
So, what is the difference ?
AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.
What Handler and AsyncTask really help you with?
The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.
That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.
Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:
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
I want to emphasize on two points:
1) Easy use of the UI thread (so, use when caller thread is UI Thread).
2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).
There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..
#: when you read Android document, you will see:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue
They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)

Android: Design consideration for performing background operation

In my application, I am parsing XML data using SAX Parser. But, I want to put the whole parsing operation in background, i.e., I want to do this using worker thread. Which will be the best solution for this, using handler, AsyncTask or services, as I am having lots of confusion between the three.
A Handler doesn't do any work; it's a means for passing off processing between a background thread and the UI thread. An AsyncTask is the way to go here: it has a built-in Handler so you can do something back on the UI thread when you're done, or even publish updates as work progresses. It's just like using a plain worker Thread, but with the convenience of the Handler built in. Of course, you can use a worker Thread and Handler yourself if the way a Handler works isn't a good match to your needs.
A Service sounds like overkill for this; it's a way to make processing available to other activities. It also doesn't get around the problem: the Service is invoked on the UI thread and it needs to fire up a separate thread to avoid blocking the UI.
You may just spawn a plain java thread and do the work there.
all have their advantage .so answer any one out of all, is depends on your need ..
like if you want easy implementation can use AsyncTask with predefined structure and callbacks and so like services may have it's own advantage in certain case ..
Handler provide more flexibility then AsyncTask as AsyncTask have predefined structure and callbacks for different work. So you can you handler with any thread with no predefined structure and callback limitation.

Categories

Resources