android component and thread, which thread to run? - android

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.

Related

Services, threads, and process

In a recent answer, I read
 A service does not run on its own thread, it runs on the UI thread
I've read similar statements in many other service-related questions.
If I call startService() from an Activity, will the Service run on the Activity's UI Thread or does it spawn a new process with it's own UI Thread?
If it runs on the Activity's UI Thread, doesn't that risk making the Activity unresponsive?
Yes services does run on main thread , About ANR(application not responding ) concern , there will higher chances of ANRs if your service is doing a long processing work using CPU so the official docs also recommends to use Worker Threads for efficiency. docs
You must read the caution paragraph in the docs to confirm
If your task is one time shot then Use IntentService which implicitly use threading mechanism for processing but IntentService will destroy itself automatically when the task is done so you will have to start it again for the next time and so.
android:process : Using this to start a service in an another process will cause usage of more memory. This will cause creating two processes for your app in separate heap memory space which also require other maintenance as well.So this is rarely used and i would not recommend to use this for a regular service task.
If I call startService() from an Activity, will the Service run on
the Activity's UI Thread or does it spawn a new process with it's
own UI Thread?
If it's a Service (not an IntentService), it will run on the main Thread of your app's process, as long as you do not define it as a separate process explicitly (by adding the android:process tag in the Manifest).
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
Yes it does, if you perform CPU intensive/blocking operations.
To prevent that, you can either start new Thread(s) from your Service, or use an IntentService, which will automatically spawn a new worker Thread for its work.
From the Services Docs it clearly explains your answer.
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise). This means that, if your
service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread
within the service to do that work. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.
In a recent answer, I read
A service does not run on its own thread, it runs on the UI thread
This is just plain wrong. A Service is an object (an instance of a class). It doesn't run on any thread, it doesn't run at all. It just "is". The methods of the Service may run on any thread, depending...
Specifically, the lifecycle methods of a Service (onCreate(), onStartCommand(), etc.) that are called directly from the Android framework run on the main (UI) thread, which may or may not be the same thread that called startService(). However, a Service can (and usually does) start other background threads, as many as it needs to, to perform the necessary work.
If I call startService() from an Activity, will the Service run on the
Activity's UI Thread or does it spawn a new process with it's own UI
Thread?
See above. If you want your Service to run in a separate process, you can do this by specifying android:process=":service" in the <service> declaration in the manifest. By default, services run in the same process as the other components (Activity, BroadcastReceiver, etc.) of your application.
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
That depends on what your Service is doing! Obviously if your Service is doing a lot of compute-intensive processing on the UI thread it will make your app unresponsive. If your Service is doing I/O on the UI thread, Android will usually throw exceptions (in more recent versions of Android). This is the reason that services usually start background threads to do work. However, if your Service is lightweight, then there is no reason why methods of your Service cannot run on the UI thread. As I said, it depends...
IntentService runs on the background thread, so, if you want to do one-off tasks then use that.

When are the default Looper and handler in main thread created

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.

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

System Service callbacks and the main thread's event loop

I was wondering what is really happening when I register a callback object with a system service. In my case I register a BluetoothGattCallback when connecting to a BLE device. I discovered that the callback is not happening on the main thread of my application when I tried to update a TextView within one of my callback methods.
My understanding is that lifecycle and other methods called by the framework are somehow (possibly through an ipc handler in Application) added to my main thread Looper's MessageQueue (event loop) and get executed on my main thread when the Looper ticks that particular message in its iteration loop.
So what is really going on when my GATT callback methods are called? When they run on a different thread does that impose concurrency? Is there some synchronization mechanism involved? Is the main thread's event loop bypassed? Or do I have a complete misunderstanding of the underlying concept?
You can have multiple threads running in the virtual machine. All of the Android lifecycle methods run on the main (UI) thread and a lot of system callbacks also run on the main thread. However, some callbacks will run on other threads, either because you ask for this behaviour or because the callbacks are programmed like that.
Since the callbacks you mention are running on other threads (not the main (UI) thread), you must make sure that you don't do anything with the UI within the code that executes in the callback methods. You can easily get around this issue by wrapping anything you do in a Runnable and run that on the main (UI) thread by calling runOnUiThread().
Regarding concurrency, that depends on your application architecture. If the code that runs in the callback methods is accessing data that you also access in code running on the main (UI) thread, then you have concurrent access to that data and you need to provide any necessary synchronization (if necessary) to avoid problems.
You ask about the main thread's event loop. If these callbacks are not running on the main (UI) thread, then they don't have anything to do with the main thead and it's event loop.
Thank you for your answer. Up to now I thought that an app by default lives in a process with just one thread. I found this clarification by Dianne Hackborn on a Google Group:
Specifically, each process has a pool of "binder threads" which sit there waiting for incoming IPCs from other process. When an IPC is dispatched to your process, one of these threads comes out of the pool to process it. These may come to you directly through an IBinder you publish from a Service to another process, semi-directly through calls from another process to a ContentProvider you have published, or indirectly from a wide range of IPCs the system does into app processes to tell it to launch an activity, receive an intent, etc.
Dianne Hackborn
Android framework engineer

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.

Categories

Resources