Does Android Service run from a separated thread instead of UI?
Copied From Android Docs :
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.
Services overview
Use IntentService
if you don't want to fiddle with managing threads on your own. Or use AsyncTasks
.
Why use Service if it runs in the same thread in android
Application main thread is not always the UI thread. For example, when Activity
is stopped, the onStop()
is invoked, hence the UI thread is taken away from that Activity
and moved to another Activity within the same or a different application. However it doesn't mean the application is no longer active, it can continue working in the background until it is closed either by OS or by user. Then who keeps it running in the background? It is the main thread and not the UI thread.
What are services
In Android, a Service is an application component that can perform
long-running operations in the background on the UI thread. By
background, it means that it doesn’t have a user interface. A Service
runs on the main thread of the calling Component’s process by default
(and hence can degrade responsiveness and cause ANRs), hence you
should create a new Thread to perform long running operations. A
Service can also be made to run in a completely different process.Unlike Activity components, Services do not have any graphical
interfaces. Also Broadcast Receivers are for receiving broadcast
messages (broadcast, multicast, unicast) and perform short tasks
whereas Services are meant to do lengthy processing like streaming
music, network transactions, file I/O, interact with databases, etc.
When a Service is started by an application component like an Activity
it runs in the background and keeps running even if the user switches
to another application or the starting component is itself destroyed
Why use service
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
Use IntentService
if you don't want to fiddle with managing threads on your own. Otherwise, use AsyncTasks
.
Please read this excellent article to understand more in detail and also read this answer.
Is it a good thing to starting service in new thread from activity
If you want your service to run on a background thread, then you have two options:
Use an
IntentService
which automatically is run on a background thread by the Android OS. Everything you do inside theIntentService
will be run on the background thread. You don't need to do any threading.Use a standard Android
Service
and instantiate anew Thread()
inside the service where you want to perform the work. The standard AndroidService
is run by default on the main thread so it will block your UI. That's why you have to handle the threading yourself.
More information here:
Android Services
Thread within Service - Android app
Will the thread still be able to run when the app is exited(click the
home button) or the phone goes to sleep?
The Thread can run in the background and also during sleep mode, but the main concern is whether service is allowed to run.
Prior to Android O you could run Service
indefinitely in background without any restrictions.
But starting from Android O, X minutes (based on my observations its around 1 - 2 minutes) after your app enters in background all the restrictions for background service will kick in and your Service will be stopped as if you have called Service.stopSelf()
If your intention is:
To run the Thread indefinitely, then you should avoid doing it, since it will impact battery life of the device and OS restriction won't permit to do it. You can perform your task periodically using WorkManager which will respect the Doze mode.
To ensure one time job started by the app to be executed until finished, then you can create the ForegroundService. Foreground service is
Service
with notification. You can consider a music player app which can play music even if you dismiss the app and control it through notification.You can follow this SO which describes the approach to start ForegroundService in Android O as well as prior versions
Why does the service run on UIThread?
the services run on the UI Thread
No, they do not.
In Java and Kotlin, objects, such as subclasses of Service
, do not run on threads. Java methods and Kotlin functions run on threads.
I assume that what you mean is "a few lifecycle methods of Service
, such as onCreate()
and onStartCommand()
, run on the main application ("UI") thread".
But why the service doesn't do it automatically?
A separate thread is not always necessary. The Service
API was created ~16 years ago. At that time, mobile CPUs were slow and threads/synchronization represented a lot of overhead.
Also, bear in mind there are lots of possible threading models (single background thread, simple thread pool, etc.) and lots of possible ways to apply them. Choosing one implementation might simplify matters for a subset of developers and add that much more overhead for everyone who needs something else.
I know that services aren't used anymore because of all the limitations
Services are widespread in Android.
Are Activity and Service running in the same thread?
Is above statement true or false?
No object "runs" on a thread, anywhere in Java. Methods run on threads.
Hence, a more accurate statement is that the lifecycle methods on Service
-- onCreate()
, onStartCommand()
, onBind()
, and onDestroy()
-- are called on the main application thread.
Can someone explain this statement from android reference for Service
I don't know how to explain that much better than it is written. While a Service
can manage a background thread, a Service
is not itself a Thread
.
If service runs in UI thread then it is not suitable for heavy work
No object "runs" on a thread, anywhere in Java. Methods run on threads.
Hence, a more accurate statement is that you should not take much time in work directly triggered by the aforementioned lifecycle methods.
If there is no activity running then in which thread service will be running?
No object "runs" on a thread, anywhere in Java. Methods run on threads.
The aforementioned lifecycle methods are called on the main application thread, regardless of whether or not there is an activity in the foreground, or even if an activity exists.
Then If I declare Handler in service as well as activity what would happen?
You would have an instance of Handler
.
Because a single Thread has one instance of Handler
The default behavior of Handler
is to tie itself to the main application thread, no matter whether you create a Handler
in an Activity
or a Service
.
Android Service and UI Thread
Use IntentService
instead of Service
. If you do network calls in a Service
, the UI will stuck. Therefore, use an IntentService
since it uses a separate Thread
.
And you do not know when a server message will retrieve the data. A NullPointerException
could be thrown if objects are accessed as long as network calls are still in progress. Use BroadcastReceiver
s to fire an Intent
whenever a server responds.
Related Topics
Android: How to Programmatically Set Layout_Constraintright_Torightof "Parent"
How to Make an Android View That Flips Between Views on Swipe/Fling
Successful Share Intent for Android
How to Debug on a Real Device (Using Eclipse/Adt)
End Incoming Call Programmatically
How to Hide The System/Navigation Bar in Android Ics
How to Forward My Localhost Ip-Address to an Android Emulator
How to Force Audio Through The Speakers When Headphones Are Plugged In
Android Studio 3.1 Edittext Stackoverflowerror
Set Visibility of Progress Bar Gone on Completion of Image Loading Using Glide Library
Adb Shell Su Works But Adb Root Does Not
How to Find Out Carrier's Name in Android
How to Pass a Message from Flutter to Native