How To Use Handler In A Service Android
A Service
is an application component that can perform long-running operations in the background. It does not provide a user interface. Once started, a service might continue running for some time, even subsequently the user switches to another awarding. Additionally, a component can demark to a service to collaborate with it and even perform interprocess advice (IPC). For instance, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
Caution: A service runs in the main thread of its hosting process; the service does non create its own thread and does non run in a separate process unless you lot specify otherwise. You should run any blocking operations on a separate thread within the service to avert Application Not Responding (ANR) errors.
Types of Services
These are the three different types of services:
- Foreground
-
A foreground service performs some performance that is noticeable to the user. For case, an audio app would use a foreground service to play an audio runway. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
When y'all use a foreground service, you must brandish a notification and so that users are actively enlightened that the service is running. This notification cannot be dismissed unless the service is either stopped or removed from the foreground.
Larn more than nigh how to configure foreground services in your app.
Notation: The WorkManager API offers a flexible fashion of scheduling tasks, and is able to run these jobs as foreground services if needed. In many cases, using WorkManager is preferable to using foreground services directly.
- Background
- A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would commonly be a background service.
Note: If your app targets API level 26 or higher, the arrangement imposes restrictions on running groundwork services when the app itself isn't in the foreground. In most situations, for example, you shouldn't access location information from the background. Instead, schedule tasks using WorkManager.
- Bound
- A service is bound when an application component binds to information technology past calling
bindService()
. A jump service offers a customer-server interface that allows components to interact with the service, transport requests, receive results, and fifty-fifty do so across processes with interprocess advice (IPC). A bound service runs only every bit long as another application component is leap to information technology. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
Although this documentation more often than not discusses started and bound services separately, your service can work both ways—information technology tin can be started (to run indefinitely) and as well allow binding. Information technology's simply a matter of whether you implement a couple of callback methods: onStartCommand()
to allow components to commencement it and onBind()
to allow binding.
Regardless of whether your service is started, bound, or both, whatever awarding component can employ the service (even from a dissever application) in the same manner that whatsoever component can utilise an activity—past starting information technology with an Intent
. Even so, yous tin can declare the service equally individual in the manifest file and block access from other applications. This is discussed more in the section well-nigh Declaring the service in the manifest.
Choosing between a service and a thread
A service is just a component that tin can run in the background, even when the user is not interacting with your application, and then you lot should create a service only if that is what you lot need.
If you must perform work exterior of your main thread, only only while the user is interacting with your application, you should instead create a new thread in the context of another awarding component. For example, if yous desire to play some music, but only while your activity is running, you lot might create a thread in onCreate()
, start running it in onStart()
, and stop it in onStop()
. Also consider using thread pools and executors from the coffee.util.concurrent
package or Kotlin coroutines instead of the traditional Thread
class. See the Threading on Android document for more information about moving execution to background threads.
Call up that if you do utilise a service, it still runs in your application's primary thread past default, so you should still create a new thread within the service if it performs intensive or blocking operations.
The basics
To create a service, you must create a subclass of Service
or use one of its existing subclasses. In your implementation, you must override some callback methods that handle key aspects of the service lifecycle and provide a mechanism that allows the components to bind to the service, if advisable. These are the nigh of import callback methods that you should override:
-
onStartCommand()
- The arrangement invokes this method by calling
startService()
when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If y'all implement this, information technology is your responsibility to stop the service when its work is consummate by callingstopSelf()
orstopService()
. If you only want to provide binding, yous don't need to implement this method. -
onBind()
- The organization invokes this method by calling
bindService()
when some other component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients apply to communicate with the service by returning anIBinder
. You must always implement this method; however, if you lot don't want to allow binding, you should render goose egg. -
onCreate()
- The system invokes this method to perform one-time setup procedures when the service is initially created (earlier information technology calls either
onStartCommand()
oronBind()
). If the service is already running, this method is non called. -
onDestroy()
- The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resource such as threads, registered listeners, or receivers. This is the last call that the service receives.
If a component starts the service by calling startService()
(which results in a call to onStartCommand()
), the service continues to run until it stops itself with stopSelf()
or another component stops it by calling stopService()
.
If a component calls bindService()
to create the service and onStartCommand()
is not called, the service runs but equally long every bit the component is bound to it. After the service is unbound from all of its clients, the organisation destroys it.
The Android organisation stops a service only when memory is low and information technology must recover system resources for the action that has user focus. If the service is bound to an activeness that has user focus, it's less probable to be killed; if the service is declared to run in the foreground, information technology's rarely killed. If the service is started and is long-running, the system lowers its position in the list of background tasks over time, and the service becomes highly susceptible to killing—if your service is started, you must pattern it to gracefully handle restarts by the system. If the system kills your service, it restarts it as shortly as resources get available, but this also depends on the value that you lot return from onStartCommand()
. For more information about when the system might destroy a service, run into the Processes and Threading document.
In the following sections, y'all'll run into how yous can create the startService()
and bindService()
service methods, as well equally how to employ them from other awarding components.
Declaring a service in the manifest
You must declare all services in your application'southward manifest file, merely as you lot practise for activities and other components.
To declare your service, add together a <service>
element as a child of the <application>
element. Here is an example:
<manifest ... > ... <awarding ... > <service android:name=".ExampleService" /> ... </application> </manifest>
See the <service>
element reference for more than information most declaring your service in the manifest.
There are other attributes that you can include in the <service>
element to define properties such as the permissions that are required to offset the service and the procedure in which the service should run. The android:name
aspect is the only required aspect—it specifies the class proper noun of the service. Later on you lot publish your application, leave this proper name unchanged to avoid the risk of breaking code due to dependence on explicit intents to start or bind the service (read the blog mail service, Things That Cannot Change).
Circumspection: To ensure that your app is secure, always apply an explicit intent when starting a Service
and don't declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot exist certain of the service that responds to the intent, and the user cannot come across which service starts. Get-go with Android v.0 (API level 21), the organization throws an exception if you call bindService()
with an implicit intent.
You lot can ensure that your service is available to only your app by including the android:exported
aspect and setting information technology to false
. This effectively stops other apps from starting your service, even when using an explicit intent.
Note: Users can encounter what services are running on their device. If they see a service that they don't recognize or trust, they can stop the service. In order to avoid having your service stopped accidentally by users, you need to add the android:clarification
aspect to the <service>
element in your app manifest. In the description, provide a short sentence explaining what the service does and what benefits it provides.
Creating a started service
A started service is one that some other component starts by calling startService()
, which results in a telephone call to the service's onStartCommand()
method.
When a service is started, information technology has a lifecycle that's contained of the component that started information technology. The service can run in the background indefinitely, even if the component that started information technology is destroyed. As such, the service should cease itself when its job is complete by calling stopSelf()
, or another component can cease information technology by calling stopService()
.
An application component such every bit an activity can outset the service by calling startService()
and passing an Intent
that specifies the service and includes any data for the service to utilise. The service receives this Intent
in the onStartCommand()
method.
For instance, suppose an activity needs to relieve some information to an online database. The activity tin beginning a companion service and evangelize it the data to save past passing an intent to startService()
. The service receives the intent in onStartCommand()
, connects to the Internet, and performs the database transaction. When the transaction is complete, the service stops itself and is destroyed.
Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same awarding, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service.
The Service
class is the base class for all services. When you extend this class, it'southward important to create a new thread in which the service can complete all of its work; the service uses your awarding's main thread past default, which tin slow the functioning of any activity that your application is running.
The Android framework likewise provides the IntentService
subclass of Service
that uses a worker thread to handle all of the start requests, ane at a time. Using this class is not recommended for new apps as it will not work well starting with Android 8 Oreo, due to the introduction of Groundwork execution limits. Moreover, it's deprecated starting with Android xi. Y'all tin can utilize JobIntentService as a replacement for IntentService
that is compatible with newer versions of Android.
The following sections depict how you tin implement your own custom service, all the same you should strongly consider using WorkManager instead for virtually utilise cases. Consult the guide to background processing on Android to come across if in that location is a solution that fits your needs.
Extending the Service class
Y'all tin can extend the Service
class to handle each incoming intent. Hither'due south how a bones implementation might look:
Kotlin
class HelloService : Service() { individual var serviceLooper: Looper? = zip private var serviceHandler: ServiceHandler? = null // Handler that receives messages from the thread private inner class ServiceHandler(looper: Looper) : Handler(looper) { override fun handleMessage(msg: Message) { // Commonly nosotros would exercise some work here, like download a file. // For our sample, we only sleep for 5 seconds. endeavor { Thread.slumber(5000) } catch (e: InterruptedException) { // Restore interrupt status. Thread.currentThread().interrupt() } // Stop the service using the startId, then that we don't end // the service in the middle of handling another job stopSelf(msg.arg1) } } override fun onCreate() { // Start up the thread running the service. Note that we create a // carve up thread because the service normally runs in the process's // principal thread, which we don't desire to cake. We also go far // background priority so CPU-intensive piece of work will non disrupt our UI. HandlerThread("ServiceStartArguments", Procedure.THREAD_PRIORITY_BACKGROUND).utilise { start() // Get the HandlerThread's Looper and apply information technology for our Handler serviceLooper = looper serviceHandler = ServiceHandler(looper) } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show() // For each start request, transport a message to start a job and deliver the // start ID so we know which asking we're stopping when we finish the task serviceHandler?.obtainMessage()?.also { msg -> msg.arg1 = startId serviceHandler?.sendMessage(msg) } // If we get killed, afterward returning from here, restart return START_STICKY } override fun onBind(intent: Intent): IBinder? { // We don't provide binding, and so return nada return nada } override fun onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).prove() } }
Java
public class HelloService extends Service { private Looper serviceLooper; individual ServiceHandler serviceHandler; // Handler that receives messages from the thread private concluding class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // Unremarkably we would do some work here, like download a file. // For our sample, nosotros only sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } // Stop the service using the startId, and then that we don't stop // the service in the center of handling another chore stopSelf(msg.arg1); } } @Override public void onCreate() { // Offset upwards the thread running the service. Note that we create a // separate thread considering the service normally runs in the procedure's // principal thread, which we don't want to block. We also get in // background priority so CPU-intensive piece of work doesn't disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.offset(); // Become the HandlerThread'south 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).evidence(); // For each get-go request, send a message to starting time a task and deliver the // start ID so nosotros know which asking nosotros're stopping when we stop the job Bulletin msg = serviceHandler.obtainMessage(); msg.arg1 = startId; serviceHandler.sendMessage(msg); // If we become killed, after returning from hither, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, and then return null return null; } @Override public void onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); } }
The case code handles all incoming calls in onStartCommand()
and posts the work to a Handler
running on a background thread. Information technology works but like an IntentService
and processes all requests serially, i after another. You lot could change the code to run the piece of work on a thread pool, for example, if you'd similar to run multiple requests simultaneously.
Notice that the onStartCommand()
method must return an integer. The integer is a value that describes how the organization should continue the service in the event that the system kills it. The return value from onStartCommand()
must exist i of the following constants:
-
START_NOT_STICKY
- If the system kills the service later
onStartCommand()
returns, practise not recreate the service unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can just restart any unfinished jobs. -
START_STICKY
- If the system kills the service later on
onStartCommand()
returns, recreate the service and callonStartCommand()
, but practise not redeliver the last intent. Instead, the organisation callsonStartCommand()
with a nix intent unless in that location are awaiting intents to start the service. In that instance, those intents are delivered. This is suitable for media players (or like services) that are not executing commands but are running indefinitely and waiting for a job. -
START_REDELIVER_INTENT
- If the system kills the service after
onStartCommand()
returns, recreate the service and telephone callonStartCommand()
with the final intent that was delivered to the service. Whatever awaiting intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.
For more details about these return values, see the linked reference documentation for each abiding.
Starting a service
You tin can start a service from an activity or other application component by passing an Intent
to startService()
or startForegroundService()
. The Android system calls the service'due south onStartCommand()
method and passes it the Intent
, which specifies which service to start.
Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService()
. That method creates a groundwork service, but the method signals to the system that the service will promote itself to the foreground. Once the service has been created, the service must call its startForeground()
method within five seconds.
For example, an activity tin can offset the instance service in the previous section (HelloService
) using an explicit intent with startService()
, as shown here:
Kotlin
Intent(this, HelloService::course.coffee).likewise { intent -> startService(intent) }
Java
Intent intent = new Intent(this, HelloService.course); startService(intent);
The startService()
method returns immediately, and the Android system calls the service'southward onStartCommand()
method. If the service isn't already running, the arrangement commencement calls onCreate()
, and then it calls onStartCommand()
.
If the service doesn't also provide binding, the intent that is delivered with startService()
is the merely mode of communication between the application component and the service. Nevertheless, if you want the service to ship a result back, the client that starts the service can create a PendingIntent
for a circulate (with getBroadcast()
) and deliver it to the service in the Intent
that starts the service. The service tin so use the circulate to deliver a event.
Multiple requests to start the service consequence in multiple corresponding calls to the service's onStartCommand()
. However, only 1 asking to finish the service (with stopSelf()
or stopService()
) is required to finish information technology.
Stopping a service
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless information technology must recover system memory and the service continues to run after onStartCommand()
returns. The service must stop itself by calling stopSelf()
, or another component tin can stop it by calling stopService()
.
Once requested to stop with stopSelf()
or stopService()
, the system destroys the service as soon equally possible.
If your service handles multiple requests to onStartCommand()
concurrently, you shouldn't stop the service when y'all're done processing a start asking, as you might have received a new commencement request (stopping at the finish of the first request would terminate the second one). To avoid this problem, y'all can use stopSelf(int)
to ensure that your request to terminate the service is e'er based on the most contempo start request. That is, when you telephone call stopSelf(int)
, you pass the ID of the start request (the startId
delivered to onStartCommand()
) to which your finish request corresponds. Then, if the service receives a new offset request earlier you lot are able to call stopSelf(int)
, the ID doesn't lucifer and the service doesn't stop.
Caution: To avert wasting system resources and consuming bombardment power, ensure that your application stops its services when it'due south done working. If necessary, other components can stop the service by calling stopService()
. Even if you lot enable binding for the service, you must e'er stop the service yourself if it ever receives a call to onStartCommand()
.
For more information about the lifecycle of a service, come across the department below nearly Managing the Lifecycle of a Service.
Creating a jump service
A bound service is one that allows application components to bind to it past calling bindService()
to create a long-standing connection. It generally doesn't allow components to start it past calling startService()
.
Create a leap service when you desire to interact with the service from activities and other components in your application or to expose some of your application'south functionality to other applications through interprocess advice (IPC).
To create a spring service, implement the onBind()
callback method to return an IBinder
that defines the interface for communication with the service. Other awarding components tin can then call bindService()
to recall the interface and begin calling methods on the service. The service lives but to serve the application component that is jump to information technology, so when there are no components bound to the service, the arrangement destroys information technology. You do not demand to stop a jump service in the aforementioned manner that you must when the service is started through onStartCommand()
.
To create a bound service, you must define the interface that specifies how a client can communicate with the service. This interface between the service and a customer must be an implementation of IBinder
and is what your service must return from the onBind()
callback method. Later the client receives the IBinder
, it can brainstorm interacting with the service through that interface.
Multiple clients tin can bind to the service simultaneously. When a client is done interacting with the service, it calls unbindService()
to unbind. When there are no clients bound to the service, the organisation destroys the service.
There are multiple ways to implement a bound service, and the implementation is more complicated than a started service. For these reasons, the bound service discussion appears in a separate document about Bound Services.
Sending notifications to the user
When a service is running, it tin notify the user of events using Toast Notifications or Status Bar Notifications.
A toast notification is a message that appears on the surface of the current window for only a moment before disappearing. A status bar notification provides an icon in the status bar with a message, which the user can select in gild to take an action (such as beginning an activity).
Normally, a status bar notification is the all-time technique to utilize when background work such as a file download has completed, and the user tin can at present human activity on information technology. When the user selects the notification from the expanded view, the notification tin start an activeness (such equally to display the downloaded file).
See the Toast Notifications or Status Bar Notifications developer guides for more data.
Managing the lifecycle of a service
The lifecycle of a service is much simpler than that of an activity. Nevertheless, it'due south even more of import that yous pay close attention to how your service is created and destroyed because a service tin run in the groundwork without the user being aware.
The service lifecycle—from when it'southward created to when information technology's destroyed—can follow either of these 2 paths:
- A started service
The service is created when another component calls
startService()
. The service then runs indefinitely and must stop itself past callingstopSelf()
. Another component can likewise stop the service by callingstopService()
. When the service is stopped, the system destroys information technology. - A bound service
The service is created when another component (a client) calls
bindService()
. The client and so communicates with the service through anIBinder
interface. The customer can shut the connection by callingunbindService()
. Multiple clients tin can bind to the same service and when all of them unbind, the system destroys the service. The service does not demand to terminate itself.
These 2 paths aren't entirely separate. You can bind to a service that is already started with startService()
. For example, you tin commencement a background music service by calling startService()
with an Intent
that identifies the music to play. Later, possibly when the user wants to practise some control over the thespian or get information about the electric current vocal, an action tin bind to the service by calling bindService()
. In cases such as this, stopService()
or stopSelf()
doesn't actually finish the service until all of the clients unbind.
Implementing the lifecycle callbacks
Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service'due south state and perform work at the advisable times. The following skeleton service demonstrates each of the lifecycle methods:
Kotlin
class ExampleService : Service() { private var startMode: Int = 0 // indicates how to behave if the service is killed individual var binder: IBinder? = null // interface for clients that bind private var allowRebind: Boolean = false // indicates whether onRebind should be used override funonCreate
() { // The service is existence created } override funonStartCommand
(intent: Intent?, flags: Int, startId: Int): Int { // The service is starting, due to a phone call to startService() return startMode } override funonBind
(intent: Intent): IBinder? { // A client is bounden to the service with bindService() return binder } override funonUnbind
(intent: Intent): Boolean { // All clients have unbound with unbindService() return allowRebind } override funonRebind
(intent: Intent) { // A client is binding to the service with bindService(), // subsequently onUnbind() has already been called } override funonDestroy
() { // The service is no longer used and is being destroyed } }
Java
public class ExampleService extends Service { int startMode; // indicates how to acquit if the service is killed IBinder binder; // interface for clients that bind boolean allowRebind; // indicates whether onRebind should be used @Override public voidonCreate
() { // The service is being created } @Override public intonStartCommand
(Intent intent, int flags, int startId) { // The service is starting, due to a phone call tostartService()
return startMode; } @Override public IBinderonBind
(Intent intent) { // A client is binding to the service withbindService()
render binder; } @Override public booleanonUnbind
(Intent intent) { // All clients have unbound withunbindService()
render allowRebind; } @Override public voidonRebind
(Intent intent) { // A customer is binding to the service withbindService()
, // afterwards onUnbind() has already been chosen } @Override public voidonDestroy
() { // The service is no longer used and is being destroyed } }
Annotation: Unlike the activity lifecycle callback methods, you lot are non required to phone call the superclass implementation of these callback methods.
Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService()
and the diagram on the right shows the lifecycle when the service is created with bindService()
.
Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService()
from those created past bindService()
, keep in mind that any service, no matter how information technology'due south started, can potentially permit clients to bind to it. A service that was initially started with onStartCommand()
(by a client calling startService()
) can still receive a call to onBind()
(when a client calls bindService()
).
By implementing these methods, you can monitor these two nested loops of the service'due south lifecycle:
- The entire lifetime of a service occurs betwixt the time that
onCreate()
is called and the time thatonDestroy()
returns. Like an activity, a service does its initial setup inonCreate()
and releases all remaining resources inonDestroy()
. For case, a music playback service can create the thread where the music is played inonCreate()
, and and so it tin can terminate the thread inonDestroy()
.Note: The
onCreate()
andonDestroy()
methods are called for all services, whether they're created bystartService()
orbindService()
. - The active lifetime of a service begins with a phone call to either
onStartCommand()
oronBind()
. Each method is handed theIntent
that was passed to eitherstartService()
orbindService()
.If the service is started, the agile lifetime ends at the same time that the entire lifetime ends (the service is yet agile fifty-fifty subsequently
onStartCommand()
returns). If the service is bound, the agile lifetime ends whenonUnbind()
returns.
Note: Although a started service is stopped by a call to either stopSelf()
or stopService()
, in that location isn't a corresponding callback for the service (at that place'south no onStop()
callback). Unless the service is bound to a client, the organization destroys it when the service is stopped—onDestroy()
is the merely callback received.
For more information about creating a service that provides binding, see the Bound Services document, which includes more information nigh the onRebind()
callback method in the section well-nigh Managing the lifecycle of a spring service.
How To Use Handler In A Service Android,
Source: https://developer.android.com/guide/components/services
Posted by: bowlinexes1998.blogspot.com
0 Response to "How To Use Handler In A Service Android"
Post a Comment