Is main thread the same as UI thread? - android

The Android doc says "Like activities and the other components, services run in the main thread of the application process."
Is the main thread here the same thing as UI thread?

Looks like it. Quoted from http://android-developers.blogspot.com/2009/05/painless-threading.html: "When an application is launched, the system creates a thread called "main" for the application. The main thread, also called the UI thread...", Official API document.

UI Thread and Main Thread are same only in Android.
The Main thread, that is responsible for handling the UI events like Draw, Listen and receive the UI events.
Ans also it is responsible for interact with running components of the UI toolkit for the corresponding application that belongs to.
When an User event occurs in the application, the Main thread *
need to add the event in the queue -> intimate about the event to
appropriate View -> change the state of the view -> redraw the view
according to the state changes -> waiting for the response for the
particular event action -> after intimated and event action completed
need to delete the event in the queue.
*
The above every actions are handled by the Main thread (Not only the above operation, it is a one of the operation handled by the UI Thread), So if our application fails to respond the event about 5 seconds android will shows the error "not responding".
So only it is widely suggested to do the light processes in the UI thread.
Hope this answer is somewhat detail and helpful to the new android bees like me.
I just shared what i learned about UI Thread. If i went wrong in anywhere please don't hesitate to recorrect me.

Basically Main Thread is Ui Thread.
However sometimes they can be different treads!
It is possible for system apps with multiple views on different threads.
Also if you use support annotations note that both #MainThread and #UiThread are available at the same time.
Here with the first one you annotate methods associated with the App life cycle and with the second one methods that are in charge of view hierarchy.
https://developer.android.com/studio/write/annotations.html

The "main application thread" is sometimes called the "UI thread".

Every Activity has its own UI thread.
As soon as the VM boots up, System Server is started by the Zygote. All other services like Activity Manager Service are started in new threads by the System Server.

Yes. main thread is UI thread.
See this tutorial for full details about background processing in android

Related

What's message queue in Android?

Can someone explain what's the message queue in Android? Is it the list of processes running? I can't find a good source explaining it.
I am asking because I was reading about the method post of the class View.
POST
added in API level 1
boolean post (Runnable action)
Causes the Runnable to be added to the message queue. The runnable
will be run on the user interface thread.
Thank you in advance.
In simple terms a MessageQueue is a list of tasks (Messages, runnables) that will be executed in a certain thread. The Android system has a very known main thread (the UI one). The method you just saw simply adds a runnable to the list of processes that will be executed in the UI thread. Alongside with Looper and Handler, MessageQueues are part of the bulding blocks of threading in Android and they are used virtually everywhere in the system.
When would you use this method?
Whenever you want to update some UI element (View element) from another thread. Maybe you're doing some heavy lifting in another thread and want to update the UI element, you can't update the UI elements in others threads but the UI thread so you post changes to be executed in the UI thread.
You can learn more about MessageQueues here and here.
to Understand MessageQueue, you need understand executing model of android app;
Just like Javascript, Cocoa in iOS, to avoid cocurrency access racing, many App related framework adapts a single thread model.
that means there is a main thread, you put your work that need be done into the queue(MessageQueue) dedicated to this thread, there is a worker(Looper) that will reteive your work from the queue, run them one by one;
this model avoid cocurrency collision in the app;
when you need do a longtime job , you should put the work into the main thread queue, when it's to do your work in the message , you create a new thread to do this longtime job, after job is done , you put a new message into the main thread message queue from your new thread;
this picture will help you understand the running model

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

What is the need of main thread in Android?

i know that the android app runs in the main thread means UI thread.I want to know what is need of main thread to run an app? What happens if we do not use the main thread to run app.Why main thread is necessary?
Well it needs a thread. Every app ever written has at least one- even the simplest Hello World app in the simplest language. A thread is just a series of instructions being run on the processor. So even if your app doesn't multithread at all, the one series of instructions it is running would be a thread- you could even call it the main thread if you wanted. So it would literally be impossible to have no main thread at all.
What makes the main thread special in Android is that you're only allowed to change visible elements on it. If Android didn't have that restriction, you'd have the possibility of race conditions and inconsistent UIs- the possibility that views are being changed on one thread while another is drawing to the screen. To prevent this you'd need to do a lot of manual locking. Instead, Android decided to only allow these changes on the main thread. That prevents a large class of timing bugs and race conditions (although not all, depending on how you implement your models).
From this link:
What is the need of main thread?
When an Android application is first started, the runtime system creates a single thread in which all application components will run by default. This thread is generally referred to as the main thread. The primary role of the main thread is to handle the user interface in terms of event handling and interaction with views in the user interface. Any additional components that are started within the application will, by default, also run on the main thread.
Why is main thread necessary?
Any component within an application that performs a time-consuming task using the main thread will cause the entire application to appear to lock up until the task is completed. This will typically result in the operating system displaying an “Application is unresponsive” warning to the user. Clearly, this is far from the desired behavior for any application. In such a situation, this can be avoided simply by launching the task to be performed in a separate thread, allowing the main thread to continue unhindered with other tasks.
Please refer to the link to understand more about main thread with an example.
For more details, you can follow this link.

How do android's Event Listeners work?

How is an event captured from a View object? There is only one thread running : the UI thread (when we haven't implemented any of our own threads). Suppose if I have implemented an onClickListener for a button and this button's function is say "cancel". For the event to be raised by the button i.e., cancel whatever the UI is doing, it must interrupt. So is that it? Do they work like interrupts?
The API guides at the developer site are beautiful explanations but still don't give the complete picture. http://developer.android.com/guide/topics/ui/ui-events.html
Internally, Android is running an event loop to handle UI events. For a nice diagram, see a third slide of this presentation. This thread is being used to dispatch system calls to the UI elements:
The system does not create a separate thread for each instance of a
component. All components that run in the same process are
instantiated in the UI thread, and system calls to each component are
dispatched from that thread.
(source: Processes and Threads)
Have a look at a Inside the Android Application Framework video from Google I/O 2008. It has the nice explanation of the event loop (consisting of Looper and Message Queue). The interesting stuff starts at around 26m into the video.
The onClick() method will be called from the same thread from which the original setOnClickListener() was called. If it was a main/UI thread, then you should be vary of performing long-running tasks in the listener - they will block the UI thread and can cause the app to be non-responsive. Use solutions like AsyncTask instead.
Please look at this blog post for detailed tutorial.
(As posted by the original questioner)
So is that it? Do they work like interrupts?
In Summary, it is not based on Interrupt (Main thread can run other code not waiting for event to happen) .. but rather based on Polling or Looping (Main thread continuously loops through to find any events or tasks are added in Message queue..)

Separate Threads for UI and Logic - Android

I want to create separate threads for implementing the core logic and updating the GUI.
Both threads should not share data with them directly. For this, i want to create a vector queue with synchronized get() and put() methods.
Suppose if an onClick event happens in the GUI thread, it notifies the core thread that it received the OnClick event. So the core thread implements something and puts the result in the vector. At this point, the GUI thread is notified of the received result and it fetches it and updates the screen.
I cant figure out how to do this. Is there a way this could be implemented?
You can do that as you would in any other framework or environment. The Android api offers you a lot of high level ways of handling multithreaded applications like you described (AsyncTask, Handler/Thread/Runnable, etc), but you can also wrap these in your own processing queue. I've done that recently where I created a logical queue for processing, and when I push something to the queue, I run a method that checks my queue for items and processes them on a background thread. You can notify the system when your processing is complete by sending broadcast intents and registering IntentFilters at the Activity level (don't forget to unregister) or you can implement your own listener interfaces the way the Android UI framework does with UI events on Views
At the heart of it though, however you wrap it, AsyncTask makes it really easy to call back and forth between background threads and the main UI thread. onPreExecute, onProgressUpdated and onPostExecute all run on the UI thread and doInBackground runs in a background thread that is automatically created for you. Doesn't get any easier than that

Categories

Resources