Android operating system is built on Linux kernel,So Linux kernel process concepts are valid for android too.
When an app component start,and the application does not have any other components running,the android system initiate a new linux process for the application with a single thread of execution.This thread is called “Main Thread” .
To identify which processes should be removed or retained,The system places each processes into an “Importance Hierarchy”.The processed with the lowest importance are removed first.
An android application automatically creates a “main” thread when it starts.This is also called the UI thread.
UI thread is used for user interaction.All android applications runs on the UI main application thread.
Running all the components on a single thread will result in poor response time.
If UI thread is blocked for morethan 5 secs ,“Application Not Responding” dialog box will reveal.
Reason for ANR?
1.Doing Network operation.
2.Performing Long Calculation.
3.Accessing Database Operation on the UI thread.
Using Background Thread?
Android UI is not “Thread-Safe”.
Should not access UI operations on outside main thread or any other Thread.
Single Thread Model
1.Don’t block the UI thread – Long running operations should not perform on UI thread,It should be done in Worker thread.
2.Don’t access UI from outside main thread.Use “Message Passing” methods.
To establish communication between main and worker thread,Android using message passing approach.
1.Handler : Handler object registers itself with the thread in which it is created.It provides a channel to send data to the thread.
2.Looper: It is a class which turns thread to pipeline thread.It implements the “loop” – It takes assigned task,execute it,then takes the next one,So on.
Use Looper class if you want to pass multiple messages.
Android Service & Background Thread ?
For Long running operation you can use either background thread or Async Task
2.Both UI and background thread runs Simultaneously.
3.Used for Performing Long running operations.
1.An application component.
2.Performs Long running operations in the background.
3.No user interface