Android Process and Resource managment - android

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

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.

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.

Android Bound Service vs. AsyncTask

I have a lot of async tasks in my activity, and I need to override AsyncTask for every call to do it async.
Can I replace all the AsyncTasks with BoundService + AIDL or I need to do it only with AsyncTask?
Service run in background but still run in main thread (AKA. UI thread), you will get ANR exception. according to API here:
Most confusion about the Service class actually revolves around what it is not:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
You can use service, but you still need implement your thread logic in either service or activity,if you want something run in a separate thread.
Service is a daemon, AsynkTask is background thread

Difference between Service, Async Task & Thread?

What is the difference between Service, Async Task & Thread. If i am not wrong all of them are used to do some stuff in background. So, how to decide which to use and when?
Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.
Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
This is the easiest answer for your question
Thread
is an unit of execution who run "parallel" to the Main Thread is an important point, you can't update a UI component from the any thread here except main thread.
AsyncTask
is a special thread, which gives you helper methods to update UI so basically you can update the UI even AsyncTask will run on a background thread. Interprocess communication handling is not required to be done explicitly.
Service
solve the above problem because it live separate from the activity that invoke it so it can continue running even when the activity is destroyed, it run in the Main Thread(beware of ANR) use a background service (extend IntentService it create the worker thread automatically for you). Service is like an activity without UI,
is good for long task
Few more information I wish someone had told me a few days ago:
You can share global variables - such as threads - between Activities and Services.
Your application together with all its global variables will not be wiped out as long as there is an Activity or a Service still present.
If you have an instance of a Service in your app and the OS needs resources, it first kills your Activities, but as long as there is the Service, the OS won't wipe out your application together with its global variables.
My use case is like this: I have one thread in global space that is connected to a server and an Activity that shows the results. When user presses the home button, the Activity goes to background and a new Service is started. This service then reads results from the thread and displays information in the notification area when needed. I don't worry about the OS destroying my Activity because I know that as long as the Service is running it won'd destroy the thread.
In short, Service for time consuming tasks, AsyncTask for short-lived tasks, Thread is a standard java construction for threads.
From developer's perspective:
Thread: Used to execute the set to codes parallely to the main thread. But you cannot handle the UI inside the thread. For that you need to use Handler. Hadler binds thread Runnable with Looper that makes it a UI thread.
ASyncTask: Used for handling those tasks that you cannot make to work on the main thread. For example, an HTTP request is a very heavy work that cannot be handled on the main thread, so you handle the HTTP request in the ASyncTask It works parallelly with your main thread Asynchronously in the background. It has a few callback methods that are invoked on their corresponding events.
Service: Works in the background under the same Application process. It is implemented when you have to do some processing that doesn't have any UI associated with it.
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

Categories

Resources