When are the default Looper and handler in main thread created - android

For the main activity, looper and handler from the main thread handle the user inputs in the UI. Since the main activity is granted one thread, when are the looper and handler created?
Is there a way to see how the underlying are implemented when it receives message from the UI and passes it down to main thread?

I'll try my best to explain the basic steps that Android goes through when it starts an application. This is a simplified answer. For more details you probably need to read the Android source code yourself.
Let's start with the user clicking on the launcher icon for your application on the HOME screen. We assume that your application is not currently running:
Android creates an OS process to host your application (since there isn't already a running OS process for your application).
Android creates the main (UI) thread and prepares a Looper and Handler for that thread and starts the Looper.
Android instantiates your singleton Application object and calls onCreate() on that instance
Android instantiates the root Activity for your application (the one with ACTION=MAIN and CATEGORY=LAUNCHER in the manifest) and calls onCreate() on that instance
Android now calls the various other lifecycle calls on your activities based on the standard lifecycle for Android components.
Once your Activity is on screen and in the foreground, UI events and other system events will be dispatched to your application's components.
In general, unless you explicitly create other threads, all of your code will run on the main (UI) thread.

Related

Android Process and Resource managment

As Per My Knowledge, In Android when Application is start , Os assign new process to app and app will running in that UIThread (mainthead) of that process.
so operation which is define under Activity Class will run on UiThread ( if we will not create separate class for any operation). and if we perform long running process we will do that task under the Service class ( Service is running even App will kill ).. So Service is running on UiThread or separate Thead? if it runs under UiThread then Why it is not affect to Ui OR if it runs under separate Thread then why we are creating another separate thread in service for long running operations?
In Android when Application is start , Os assign new process to app
Correct.
app will running in that UIThread (mainthead) of that process
Incorrect. An "app" does not run on any thread. Methods of Java objects are called on threads.
so operation which is define under Activity Class will run on UiThread
Incorrect. A Java class does not run on any thread. Methods of Java objects are called on threads. Hence, methods of an activity will be called on threads. Some of those methods will be called on the main application thread (a.k.a., UI thread) of the Android app's process.
So Service is running on UiThread or separate Thead?
Neither, or both, depending upon how you want to look at it. Again, a Java class does not run on any thread. Methods of Java objects are called on threads. The lifecycle methods of a service (e.g., onCreate(), onStartCommand(), onDestroy()) are called on the main application thread. onHandleIntent() of an IntentService is called on a background thread.
if it runs under UiThread then Why it is not affect to Ui
Any time you spend in your code on the main application thread will freeze the UI. It does not matter whether the code is a method on an activity, a method on a service, or a method on something else.
if it runs under separate Thread then why we are creating another separate thread in service for long running operations?
To avoid tying up the main application thread and thereby freezing the UI.
Services runs on UI thread. Also in some way it can interact with UI.
Here is a good starting article.
http://developer.android.com/guide/components/services.html

What are lifecycles of threads started from: Activity , UI less Fragment , Service (started, binded)?

What are lifecycles of threads (f.i. consider a thread for playing music) started from:
Activity
UI less Fragment
Service (started, binded)
When threads will be destroyed?
When to use Service and UI less Fragment for background tasks?
Activity => till android kills your process or the run method of your thread returns.
UI less Fragment => same as above.
Service started => till call to stopSelf or stopService or the run method of your thread returns.
binded => till all client unbind from it or the run method of your thread returns.
When to use Service and UI less Fragment for background tasks?
Service => long running operation regardless of having any UI.
UI less Fragment for background tasks => it is a design pattern to store your objects and preventing from creating another object (or in your context another thread) when activity is recreated. in this pattern you can access your thread reference regardless of activity is recreated or not. if for example you declare your thread in onCreate method, if you change the orientation 5 times you create 5 different threads, that may cause memory leak.
all above situation in one sentence is:
the thread runs till android kills the process or the thread returns from its run method.
When threads will be destroyed?
From the documentation:
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread)
... However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.
When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events.
Because of the single thread model described above, it's vital to the responsiveness of your application's UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads).
Anyway you should read the whole documentation page.

android component and thread, which thread to run?

android don't have a "main" method, so all component of android app, such as activity, content provider can be run by the android system in response to other app's request.
So, suppose at the nearly sometime, two app request two component of ONE app.
my question is will those component running in one thread or different thread?
Most interactions between the OS and the application run on the main thread (AKA UI Thread).
It doesnt matter how many "requests" the app receive at the same time, all the "requests" are processed by a looper in the main thread.
You could add tasks to this main thread looper from any thread in your app:
Runnable task = buildYourTask();
new Handler(Looper.getMainLooper()).post(task);
[Update]
This is from android developer documentation:
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. Consequently, methods that respond to
system callbacks (such as onKeyDown() to report user actions or a
lifecycle callback method) always run in the UI thread of the process.
Components do not run on threads. Objects do not run on threads. Methods run on threads.
The lifecycle methods of a component, such as onCreate() of an activity, run on the main application thread.

how local service is running in MainThread without affecting UI operations

I am lagging in basic android concept,
As per the documentation Service is running in MainThread. and Activity(UI) also running in same thread. In what way MainThread in the android application is running both components code (Service and Activity) paralelly. How android is handling this as local Service is not a separate process. Please give me detailed explanation or any specific links
You'll notice most, if not all of the "main UI thread" methods you write, are callbacks -- they are not running any single main loop, but rather are called when needed, to perform bried tasks (ie: change UI). There is clearly an android main loop that is listening and trigerring these methods.
That same android main loop sometimes also runs Services and Handler code.
As a result, basic simple Services should not kick off extended work loops, as that would prevent focus getting back to the UI methods.
Finally, if a UI method (or Service or Handler) starts doing a lot of work, the android main loop will trigger an Application Not Responding (ANR) to kill the app.

Android Background threads: Difference between launching from an Activity and from a Service

Is there any difference in running background threads from an Activity and from a Service that is started by the Activity? Added: The background threads do not interact with the UI.
I currently have some background threads that are launched from the Activity. Most are via AsyncTask and one is through my own ExecutorService. I would like to know if there is a significant benefit to refactoring the code to move these to a Service or IntentService.
You seem to be confused about the definition of Activities and Services. To make it clear:
Activities are things that run according to the Activity lifecycle state machine. The code in the respective handlers interacts with an event loop attached to a UI.
Services are things that run according to the Service lifecycle state machine. The code in the respective lifecycle handlers performs operations to handle things like Intents, etc..., but does not interact with the user via a UI.
Both of these, however, run on the "main thread" of the application. By itself, an Activity or a Service (or Broadcast Receiver, Content provider, etc...) is not a thread. Look at the documentation, and you will see that the Activity and Service classes do not, in fact, form a thread. Instead, they are hooks that will run inside the Android framework, and the framework will at the appropriate time call them on the "main" thread of the app.
You can create separate threads for the app, or use an AsyncTask to do work and publish it to the UI thread easily (something not so easily achieved with a Service).
Threads that are bound to Activities have the same lifecycle. So if you restart/kill the Activity, the thread will also be restarted/killed. This is a problem if you don't manage the lifecycle of an Activity. A service is good in this case. You can have the activity destroyed and still a worker thread running in the background (in the service). But be advised that, if the Android system need resources (memory for example) it will kill the services first (and then restart them according to their Sticky flag). In my opinion, there are no actual benefit in changing threads from the Activity to a Service, since you control the workflow of your activity. If the threads are heavy (and brake the UI for moments) consider putting them in a service on a separate process (in AndroidManifest put the process name of the service).
In Android documentation:
Caution: Another problem you might encounter when using a worker
thread is unexpected restarts in your activity due to a runtime
configuration change (such as when the user changes the screen
orientation), which may destroy your worker thread. To see how you can
persist your task during one of these restarts and how to properly
cancel the task when the activity is destroyed, see the source code
for the Shelves sample application.

Categories

Resources