What is the need of main thread in Android? - 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.

Related

Identify application slowness due to Android OS

How do I check why an application is running slow? More precisely, which lifecycle method is taking more time to execute in Android.
I have already tried logging the lifecycle methods of each activity and fragment, but I could not figure out the reason for the delay.
The onCreate is called, but then there is quite a delay (around 1s) before onResume is called.
Owing to the above delay, the user feels like the application is not very responsive.
The delay is reduced to about 100ms for high end phones. But it the old 2012-2011 models that have this huge delay.
A few ideas on how to investigate further into identifying the root cause of delays, and how could we optimise apps to navigate through screens faster.
Thanks in advance.
If you are processing heavy load of data (including complex UI rendering) in main thread , then you can find this kind of message in logcat:
W/Trace(1274): Unexpected value from nativeGetEnabledTags: 0
I/Choreographer(1274): Skipped 55 frames! The application may be doing too much work on its main thread.
This may cause your application to slow down with respect to rendering
UI
Suggestable Fix
Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread
Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.
So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.
So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.

What is the difference between thread and service in android , when downloading an image

What is the difference between thread and service in android,when downloading an image
There are lots of difference between Normal thread and a Service
Service: Due to android component it runs on UI thread but without any view shown to user. It runs in background with the same kind of property that an activity have, like you cannot run network operations (downloading image, calling web service) in service for that you have to use Thread which will run on worker thread other than UI thread.
Thread: Its an independent path of execution which can consist network operation, complex coding, huge amount of data transfer and accept. Thread is not related to android but in android it is used to perform different task. You can download an image on Thread but to show it on any UI part you have to update downloaded image on UI thread using runOnUIThread method
Please let me know if this explanation clears your doubt. If not let me know which part you did not understand and what exactly is your question.
With rare exceptions, you should never explicitly create a Thread. Threads are expensive and prone to programmer error. Use AsyncTask because it handles the complexity of thread safety and provides the optimization of thread pooling. Or better yet, if network activity is your reason for doing work outside the main thread, use one of the many network libraries that manages all of these concerns for you. Which approach is fastest is not something that can be answered generally, and should never even be a concern until you've tried the simple and clear solution and demonstrated that its performance is inadequate.
Regardless of how you make your network activity asynchronous, any network activity that is not started and completed (or cancelled) within the lifetime of a single Activity instance needs to be hosted in something else. If it only needs to survive across configuration changes, host it in a retained Fragment. If it needs to survive between different activities, host it in a Service. When choosing between these options, remember that your Activity may be destroyed any time it goes into the background or backstack.

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)

Why is a single threaded model used to update the UI as main thread?

The Qt doc says,
As mentioned, each program has one thread when it is started. This
thread is called the "main thread" (also known as the "GUI thread" in
Qt applications). The Qt GUI must run in this thread.
The Android doc says,
Like activities and the other components, services run in the main
thread of the application process
And iOS,
It is strongly recommended not to update UI controls etc from a
background thread (e.g. a timer, comms etc). This can be the cause of
crashes which are sometimes very hard to identify. Instead use these
to force code to be executed on the UI thread (which is always the
“main” thread).
Why does they use a single threaded model to update UI ?
The short answer is, it's the only reasonable way to ensure that the display is not corrupted.
The long answer is that allowing multiple threads to update the UI results in deadlocks, race conditions, and all sorts of trouble. This was the painful lesson taught by Java's AWT (among other UI systems) that allows multiple threads to touch the UI. See, for instance, Multithreaded toolkits: A failed dream?. That post refers (via dead links) to Why Threads Are A Bad Idea and Threadaches.
iOS and Android force you to work with UI only from main thread. The reason is the same as a shared object, thread safe[About]... in multithread environment
Android example error
FATAL EXCEPTION: Thread-19449
E/AndroidRuntime: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
iOS example error
This application is modifying the autolayout engine from a background thread" error?

Is main thread the same as UI thread?

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

Categories

Resources