A Service
is an
utility element that may carry out
long-running operations within the background. It doesn’t present a person interface. As soon as
began, a service may proceed working for a while, even after the person switches to a different
utility. Moreover, a element can bind to a service to work together with it and even carry out
interprocess communication (IPC). For instance, a service can deal with community transactions, play
music, carry out file I/O, or work together with a content material supplier, all from the background.
Warning: A service runs in the primary thread of its internet hosting
course of; the service does not create its personal thread and does not
run in a separate course of until you specify in any other case. It is best to run any blocking operations on
a separate thread inside the service to keep away from Software
Not Responding (ANR) errors.
Varieties of Providers
These are the three several types of providers:
- Foreground
-
A foreground service performs some operation that’s noticeable to the
person. For instance, an audio app would use a foreground service to play an
audio monitor. Foreground providers should show a Notification.
Foreground providers proceed working even when the person is not interacting
with the app.While you use a foreground service, you need to show a notification in order that
customers are actively conscious that the service is working. This notification can not
be dismissed until the service is both stopped or faraway from the
foreground.Study extra about the way to configure
foreground providers in your
app.Be aware: The
WorkManager API provides a versatile manner of scheduling duties, and is
capable of run
these jobs as foreground providers if wanted. In lots of instances, utilizing
WorkManager is preferable to utilizing foreground providers straight. - Background
- A background service performs an operation that is not straight observed by
the person. For instance, if an app used a service to compact its storage,
that may normally be a background service.Be aware: In case your app targets API degree 26 or greater, the system imposes restrictions on working background
providers when the app itself is not within the foreground. In most
conditions, for instance, you should not
entry location info from the
background. As an alternative,
schedule duties utilizing
WorkManager. - Sure
- A service is sure when an utility element binds to it by calling
bindService()
. A sure service provides a client-server
interface that enables elements to work together with the service, ship requests, obtain outcomes,
and even accomplish that throughout processes with interprocess communication (IPC). A sure service runs solely
so long as one other utility element is sure to it. A number of elements can bind to the
service without delay, however when all of them unbind, the service is destroyed.
Though this documentation usually discusses began and sure providers individually,
your service can work each methods—it may be began (to run indefinitely) and in addition enable
binding. It is merely a matter of whether or not you implement a few callback strategies: onStartCommand()
to permit elements to start out it and onBind()
to permit binding.
No matter whether or not your service is began, sure, or each, any utility element
can use the service (even from a separate utility) in the identical manner that any element can use
an exercise—by beginning it with an Intent
. Nonetheless, you possibly can declare
the service as personal within the manifest file and block entry from different functions.
That is mentioned extra within the part about Declaring the service within the
manifest.
Selecting between a service and a thread
A service is just a element that may run within the background, even when the person just isn’t
interacting along with your utility, so you must create a service provided that that’s what you
want.
Should you should carry out work outdoors of your foremost thread, however solely whereas the person is interacting
along with your utility, you must as an alternative create a brand new thread within the context of one other utility
element. For instance, if you wish to play some music, however solely whereas your exercise is working,
you may create a thread in onCreate()
,
begin working it in onStart()
,
and cease it in onStop()
.
Additionally think about using thread swimming pools and executors from the java.util.concurrent
bundle
or Kotlin coroutines as an alternative of the standard
Thread
class. See the
Threading on Android doc for extra details about
shifting execution to background threads.
Do not forget that if you happen to do use a service, it nonetheless runs in your utility’s foremost thread by
default, so you must nonetheless create a brand new thread inside the service if it performs intensive or
blocking operations.
The fundamentals
To create a service, you need to create a subclass of Service
or use one
of its current subclasses. In your implementation, you need to override some callback strategies that
deal with key elements of the service lifecycle and supply a mechanism that enables the elements to
bind to the service, if applicable. These are crucial callback strategies that you must
override:
onStartCommand()
- The system invokes this technique by calling
startService()
when one other element (reminiscent of an exercise) requests that the service be began.
When this technique executes, the service is began and might run within the
background indefinitely. Should you implement this, it’s your accountability to cease the service when
its work is full by callingstopSelf()
orstopService()
. Should you solely need to present binding, you do not
must implement this technique. onBind()
- The system invokes this technique by calling
bindService()
when one other element desires to bind with the service (reminiscent of to carry out RPC).
In your implementation of this technique, you need to present an interface that shoppers
use to speak with the service by returning anIBinder
. You will need to all the time
implement this technique; nonetheless, if you happen to do not need to enable binding, you must return
null. onCreate()
- The system invokes this technique to carry out one-time setup procedures when the service is
initially created (earlier than it calls both
onStartCommand()
or
onBind()
). If the service is already working, this technique just isn’t
referred to as. onDestroy()
- The system invokes this technique when the service is not used and is being destroyed.
Your service ought to implement this to scrub up any assets reminiscent of threads, registered
listeners, or receivers. That is the final name that the service receives.
If a element begins the service by calling startService()
(which ends up in a name to onStartCommand()
), the service
continues to run till it stops itself with stopSelf()
or one other
element stops it by calling stopService()
.
If a element calls
bindService()
to create the service and onStartCommand()
just isn’t referred to as, the service runs
solely so long as the element is sure to it. After the service is unbound from all of its shoppers,
the system destroys it.
The Android system stops a service solely when reminiscence is low and it should recuperate system
assets for the exercise that has person focus. If the service is sure to an exercise that has person
focus, it is much less more likely to be killed; if the service is said to run within the foreground, it is hardly ever killed.
If the service is began and is long-running, the system lowers its place
within the listing of background duties over time, and the service turns into extremely vulnerable to
killing—in case your service is began, you need to design it to gracefully deal with restarts
by the system. If the system kills your service, it restarts it as quickly as assets turn out to be
accessible, however this additionally is dependent upon the worth that you simply return from onStartCommand()
. For extra info
about when the system may destroy a service, see the Processes and Threading
doc.
Within the following sections, you may see how one can create the
startService()
and
bindService()
service strategies, in addition to the way to use
them from different utility elements.
Declaring a service within the manifest
You will need to declare all providers in your utility’s
manifest file, simply as you do for actions and different elements.
To declare your service, add a <service>
factor
as a toddler of the <utility>
factor. Right here is an instance:
<manifest ... > ... <utility ... > <service android_name=".ExampleService" /> ... </utility> </manifest>
See the <service>
factor
reference for extra details about declaring your service within the manifest.
There are different attributes which you can embrace within the <service>
factor to
outline properties such because the permissions which are required to start out the service and the method in
which the service ought to run. The android:title
attribute is the one required attribute—it specifies the category title of the service. After
you publish your utility, depart this title unchanged to keep away from the chance of breaking
code as a consequence of dependence on specific intents to start out or bind the service (learn the weblog put up, Issues
That Can’t Change).
Warning: To make sure that your app is safe, all the time use an
specific intent when beginning a Service
and do not declare intent filters for
your providers. Utilizing an implicit intent to start out a service is a safety hazard since you can not
make sure of the service that responds to the intent, and the person can not see which service
begins. Starting with Android 5.0 (API degree 21), the system throws an exception if you happen to name
bindService()
with an implicit intent.
You possibly can be certain that your service is offered to solely your app by
together with the android:exported
attribute and setting it to false
. This successfully stops different apps from beginning your
service, even when utilizing an specific intent.
Be aware:
Customers can see what providers are working on their gadget. In the event that they see
a service that they do not acknowledge or belief, they’ll cease the service. In
order to keep away from having your service stopped unintentionally by customers, you want
so as to add the
android:description
attribute to the
<service>
factor in your app manifest. Within the description,
present a brief sentence explaining what the service does and what advantages
it offers.
Making a began service
A began service is one which one other element begins by calling startService()
, which ends up in a name to the service’s
onStartCommand()
technique.
When a service is began, it has a lifecycle that is unbiased of the
element that began it. The service can run within the background indefinitely, even when
the element that began it’s destroyed. As such, the service ought to cease itself when its job
is full by calling stopSelf()
, or one other element can
cease it by calling stopService()
.
An utility element reminiscent of an exercise can begin the service by calling startService()
and passing an Intent
that specifies the service and consists of any knowledge for the service to make use of. The service receives
this Intent
within the onStartCommand()
technique.
As an example, suppose an exercise wants to avoid wasting knowledge to an internet database. The exercise
can begin a companion service and ship it the info to save lots of by passing an intent to startService()
. The service receives the intent in onStartCommand()
, connects to the Web, and performs the
database transaction. When the transaction is full, the service stops itself and is
destroyed.
Warning: A service runs in the identical course of as the applying
through which it’s declared and in the primary thread of that utility by default. In case your service
performs intensive or blocking operations whereas the person interacts with an exercise from the identical
utility, the service slows down exercise efficiency. To keep away from impacting utility
efficiency, begin a brand new thread contained in the service.
The Service
class is the bottom
class for all providers. While you prolong this class, it is essential to create a brand new thread through which
the service can full all of its work; the service makes use of your utility’s foremost thread by
default, which may sluggish the efficiency of any exercise that your utility is working.
The Android framework additionally offers the IntentService
subclass of Service
that makes use of a
employee thread to deal with the entire begin requests, separately. Utilizing this class is not
advisable for brand new apps because it is not going to work properly beginning with Android 8 Oreo, as a result of
introduction of Background execution limits.
Furthermore, it is deprecated beginning with Android 11.
You need to use JobIntentService as a
substitute for IntentService
that’s suitable with newer variations of Android.
The next sections describe how one can implement your personal customized service, nonetheless you must
strongly think about using WorkManager as an alternative for many use instances. Seek the advice of the information to background processing on Android
to see if there’s a resolution that matches your wants.
Extending the Service class
You possibly can prolong the Service
class
to deal with every incoming intent. Here is how a primary implementation may look:
Kotlin
class HelloService : Service() { personal var serviceLooper: Looper? = null personal var serviceHandler: ServiceHandler? = null // Handler that receives messages from the thread personal internal class ServiceHandler(looper: Looper) : Handler(looper) { override enjoyable handleMessage(msg: Message) { // Usually we might do some work right here, like obtain a file. // For our pattern, we simply sleep for five seconds. attempt { Thread.sleep(5000) } catch (e: InterruptedException) { // Restore interrupt standing. Thread.currentThread().interrupt() } // Cease the service utilizing the startId, in order that we do not cease // the service in the midst of dealing with one other job stopSelf(msg.arg1) } } override enjoyable onCreate() { // Begin up the thread working the service. Be aware that we create a // separate thread as a result of the service usually runs within the course of's // foremost thread, which we do not need to block. We additionally make it // background precedence so CPU-intensive work is not going to disrupt our UI. HandlerThread("ServiceStartArguments", Course of.THREAD_PRIORITY_BACKGROUND).apply { begin() // Get the HandlerThread's Looper and use it for our Handler serviceLooper = looper serviceHandler = ServiceHandler(looper) } } override enjoyable onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).present() // For every begin request, ship a message to start out a job and ship the // begin ID so we all know which request we're stopping once we end the job serviceHandler?.obtainMessage()?.additionally { msg -> msg.arg1 = startId serviceHandler?.sendMessage(msg) } // If we get killed, after coming back from right here, restart return START_STICKY } override enjoyable onBind(intent: Intent): IBinder? { // We do not present binding, so return null return null } override enjoyable onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).present() } }
Java
public class HelloService extends Service { personal Looper serviceLooper; personal ServiceHandler serviceHandler; // Handler that receives messages from the thread personal last class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { tremendous(looper); } @Override public void handleMessage(Message msg) { // Usually we might do some work right here, like obtain a file. // For our pattern, we simply sleep for five seconds. attempt { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt standing. Thread.currentThread().interrupt(); } // Cease the service utilizing the startId, in order that we do not cease // the service in the midst of dealing with one other job stopSelf(msg.arg1); } } @Override public void onCreate() { // Begin up the thread working the service. Be aware that we create a // separate thread as a result of the service usually runs within the course of's // foremost thread, which we do not need to block. We additionally make it // background precedence so CPU-intensive work does not disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Course of.THREAD_PRIORITY_BACKGROUND); thread.begin(); // Get the HandlerThread's Looper and use it for our Handler serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(serviceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).present(); // For every begin request, ship a message to start out a job and ship the // begin ID so we all know which request we're stopping once we end the job Message msg = serviceHandler.obtainMessage(); msg.arg1 = startId; serviceHandler.sendMessage(msg); // If we get killed, after coming back from right here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We do not present binding, so return null return null; } @Override public void onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).present(); } }
The instance code handles all incoming calls in onStartCommand()
and posts the work to a Handler
working on a background thread. It really works similar to an IntentService
and processes all requests serially, one after one other.
You would change the code to run the work on a thread pool, for instance, if you would like to run a number of requests concurrently.
Discover that the onStartCommand()
technique should return an
integer. The integer is a worth that describes how the system ought to proceed the service within the
occasion that the system kills it. The return worth
from onStartCommand()
have to be one of many following
constants:
START_NOT_STICKY
- If the system kills the service after
onStartCommand()
returns, don’t recreate the service until there are pending
intents to ship. That is the most secure choice to keep away from working your service when not essential
and when your utility can merely restart any unfinished jobs. START_STICKY
- If the system kills the service after
onStartCommand()
returns, recreate the service and nameonStartCommand()
, however don’t redeliver the final intent.
As an alternative, the system callsonStartCommand()
with a
null intent until there are pending intents to start out the service. In that case,
these intents are delivered. That is appropriate for media gamers (or comparable providers) that aren’t
executing instructions however are working indefinitely and ready for a job. START_REDELIVER_INTENT
- If the system kills the service after
onStartCommand()
returns, recreate the service and nameonStartCommand()
with the final intent that was delivered to the
service. Any pending intents are delivered in flip. That is appropriate for providers which are
actively performing a job that needs to be instantly resumed, reminiscent of downloading a file.
For extra particulars about these return values, see the linked reference
documentation for every fixed.
Beginning a service
You can begin a service from an exercise or different utility element by
passing an Intent
to startService()
or startForegroundService()
. The
Android system calls the service’s onStartCommand()
technique and passes it the Intent
,
which specifies which service to start out.
Be aware: In case your app targets API degree 26 or greater, the system
imposes restrictions on utilizing or creating background providers until the app
itself is within the foreground. If an app must create a foreground service,
the app ought to name startForegroundService()
. That technique creates a background service, however the
technique indicators to the system that the service will promote itself to the
foreground. As soon as the service has been created, the service should name its
startForeground()
technique inside
5 seconds.
For instance, an exercise can begin the instance service within the earlier part (HelloService
) utilizing an specific intent with startService()
, as proven right here:
Kotlin
Intent(this, HelloService::class.java).additionally { intent -> startService(intent) }
Java
Intent intent = new Intent(this, HelloService.class); startService(intent);
The startService()
technique returns instantly, and
the Android system calls the service’s onStartCommand()
technique. If the service is not already working, the system first calls onCreate()
, after which it calls
onStartCommand()
.
If the service does not additionally present binding, the intent that’s delivered with startService()
is the one mode of communication between the
utility element and the service. Nonetheless, if you would like the service to ship a end result again,
the consumer that begins the service can create a PendingIntent
for a broadcast
(with getBroadcast()
) and ship it to the service
within the Intent
that begins the service. The service can then use the
broadcast to ship a end result.
A number of requests to start out the service end in a number of corresponding calls to the service’s
onStartCommand()
. Nonetheless, just one request to cease
the service (with stopSelf()
or stopService()
) is required to cease it.
Stopping a service
A began service should handle its personal lifecycle. That’s, the system does not cease or
destroy the service until it should recuperate system reminiscence and the service
continues to run after onStartCommand()
returns. The
service should cease itself by calling stopSelf()
, or one other
element can cease it by calling stopService()
.
As soon as requested to cease with stopSelf()
or stopService()
, the system destroys the service as quickly as
attainable.
In case your service handles a number of requests to onStartCommand()
concurrently, you should not cease the
service whenever you’re carried out processing a begin request, as you may need acquired a brand new
begin request (stopping on the finish of the primary request would terminate the second). To keep away from
this downside, you should use stopSelf(int)
to make sure that your request to
cease the service is all the time based mostly on the latest begin request. That’s, whenever you name stopSelf(int)
, you go the ID of the beginning request (the startId
delivered to onStartCommand()
) to which your cease request
corresponds. Then, if the service receives a brand new begin request earlier than you’ll be able to name stopSelf(int)
, the ID does not match and the service does not cease.
Warning: To keep away from losing system assets and consuming
battery energy, be certain that your utility stops its providers when it is carried out working.
If essential, different elements can cease the service by calling stopService()
. Even if you happen to allow binding for the service,
you need to all the time cease the service your self if it ever receives a name to onStartCommand()
.
For extra details about the lifecycle of a service, see the part under about Managing the Lifecycle of a Service.
Making a sure service
A sure service is one that enables utility elements to bind to it by calling bindService()
to create a long-standing connection.
It usually does not enable elements to start out it by calling startService()
.
Create a sure service whenever you need to work together with the service from actions
and different elements in your utility or to show a few of your utility’s performance to
different functions via interprocess communication (IPC).
To create a sure service, implement the onBind()
callback technique to return an IBinder
that
defines the interface for communication with the service. Different utility elements can then name
bindService()
to retrieve the interface and
start calling strategies on the service. The service lives solely to serve the applying element that
is sure to it, so when there aren’t any elements sure to the service, the system destroys it.
You do not want to cease a sure service in the identical manner that you need to when the service is
began via onStartCommand()
.
To create a sure service, you need to outline the interface that specifies how a consumer can
talk with the service. This interface between the service
and a consumer have to be an implementation of IBinder
and is what your service should
return from the onBind()
callback technique. After the consumer receives the IBinder
, it will possibly start
interacting with the service via that interface.
A number of shoppers can bind to the service concurrently. When a consumer is finished interacting with
the service, it calls unbindService()
to unbind.
When there aren’t any shoppers sure to the service, the system destroys the service.
There are a number of methods to implement a sure service, and the implementation is extra
sophisticated than a began service. For these causes, the sure service dialogue seems in a
separate doc about Sure Providers.
Sending notifications to the person
When a service is working, it will possibly notify the person of occasions utilizing Toast Notifications or Standing Bar Notifications.
A toast notification is a message that seems on the floor of the present window for less than a
second earlier than disappearing. A standing bar notification offers an icon within the standing bar with a
message, which the person can choose as a way to take an motion (reminiscent of begin an exercise).
Normally, a standing bar notification is the very best method to make use of when background work reminiscent of
a file obtain has accomplished, and the person can now act on it. When the person
selects the notification from the expanded view, the notification can begin an exercise
(reminiscent of to show the downloaded file).
See the Toast Notifications or Standing Bar Notifications
developer guides for extra info.
Managing the lifecycle of a service
The lifecycle of a service is far easier than that of an exercise. Nonetheless, it is much more
essential that you simply pay shut consideration to how your service is created and destroyed as a result of a
service can run within the background with out the person being conscious.
The service lifecycle—from when it is created to when it is destroyed—can observe
both of those two paths:
- A began service
The service is created when one other element calls
startService()
. The service then runs indefinitely and should
cease itself by callingstopSelf()
. One other element can even cease the
service by callingstopService()
. When the service is stopped, the system destroys it. - A sure service
The service is created when one other element (a consumer) calls
bindService()
. The consumer then communicates with the service
via anIBinder
interface. The consumer can shut the connection by calling
unbindService()
. A number of shoppers can bind to
the identical service and when all of them unbind, the system destroys the service. The service
doesn’t must cease itself.
These two paths aren’t fully separate. You possibly can bind to a service that’s already
began with startService()
. For instance, you possibly can
begin a background music service by calling startService()
with an Intent
that identifies the music to play. Later,
presumably when the person desires to train some management over the participant or get details about the
present track, an exercise can bind to the service by calling bindService()
. In instances reminiscent of this, stopService()
or stopSelf()
does not truly cease the service till the entire shoppers unbind.
Implementing the lifecycle callbacks
Like an exercise, a service has lifecycle callback strategies which you can implement to observe
adjustments within the service’s state and carry out work on the applicable occasions. The next skeleton
service demonstrates every of the lifecycle strategies:
Kotlin
class ExampleService : Service() { personal var startMode: Int = 0 // signifies the way to behave if the service is killed personal var binder: IBinder? = null // interface for shoppers that bind personal var allowRebind: Boolean = false // signifies whether or not onRebind needs to be used override enjoyableonCreate
() { // The service is being created } override enjoyableonStartCommand
(intent: Intent?, flags: Int, startId: Int): Int { // The service is beginning, as a consequence of a name to startService() return startMode } override enjoyableonBind
(intent: Intent): IBinder? { // A consumer is binding to the service with bindService() return binder } override enjoyableonUnbind
(intent: Intent): Boolean { // All shoppers have unbound with unbindService() return allowRebind } override enjoyableonRebind
(intent: Intent) { // A consumer is binding to the service with bindService(), // after onUnbind() has already been referred to as } override enjoyableonDestroy
() { // The service is not used and is being destroyed } }
Java
public class ExampleService extends Service { int startMode; // signifies the way to behave if the service is killed IBinder binder; // interface for shoppers that bind boolean allowRebind; // signifies whether or not onRebind needs to be used @Override public voidonCreate
() { // The service is being created } @Override public intonStartCommand
(Intent intent, int flags, int startId) { // The service is beginning, as a consequence of a name tostartService()
return startMode; } @Override public IBinderonBind
(Intent intent) { // A consumer is binding to the service withbindService()
return binder; } @Override public booleanonUnbind
(Intent intent) { // All shoppers have unbound withunbindService()
return allowRebind; } @Override public voidonRebind
(Intent intent) { // A consumer is binding to the service withbindService()
, // after onUnbind() has already been referred to as } @Override public voidonDestroy
() { // The service is not used and is being destroyed } }
Be aware: In contrast to the exercise lifecycle callback strategies, you’re
not required to name the superclass implementation of those callback strategies.
Determine 2. The service lifecycle. The diagram on the left
reveals the lifecycle when the service is created with startService()
and the diagram on the appropriate reveals the lifecycle when the service is created
with bindService()
.
Determine 2 illustrates the everyday callback strategies for a service. Though the determine separates
providers which are created by startService()
from these
created by bindService()
, maintain
in thoughts that any service, regardless of the way it’s began, can doubtlessly enable shoppers to bind to it.
A service that was initially began with onStartCommand()
(by a consumer calling startService()
)
can nonetheless obtain a name to onBind()
(when a consumer calls
bindService()
).
By implementing these strategies, you possibly can monitor these two nested loops of the service’s
lifecycle:
- The whole lifetime of a service happens between the time that
onCreate()
is known as and the time thatonDestroy()
returns. Like an exercise, a service does its preliminary setup in
onCreate()
and releases all remaining assets inonDestroy()
. For instance, a
music playback service can create the thread the place the music is performed inonCreate()
, after which it will possibly cease the thread inonDestroy()
.Be aware: The
onCreate()
andonDestroy()
strategies are referred to as for all providers, whether or not
they’re created bystartService()
orbindService()
. - The energetic lifetime of a service begins with a name to both
onStartCommand()
oronBind()
.
Every technique is handed theIntent
that was handed to bothstartService()
orbindService()
.If the service is began, the energetic lifetime ends on the identical time that your entire lifetime
ends (the service remains to be energetic even afteronStartCommand()
returns). If the service is sure, the energetic lifetime ends whenonUnbind()
returns.
Be aware: Though a began service is stopped by a name to
both stopSelf()
or stopService()
, there is not a respective callback for the
service (there is not any onStop()
callback). Until the service is sure to a consumer,
the system destroys it when the service is stopped—onDestroy()
is the one callback acquired.
For extra details about making a service that gives binding, see the Sure Providers doc,
which incorporates extra details about the onRebind()
callback technique within the part about Managing the lifecycle of
a sure service.