banner



How To Access Running Service New Android Update

A Service is an awarding component that tin perform long-running operations in the background. It does not provide a user interface. Once started, a service might proceed running for some time, even later the user switches to another application. Additionally, a component can bind to a service to collaborate with it and fifty-fifty perform interprocess advice (IPC). For example, a service tin can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the groundwork.

Circumspection: A service runs in the chief thread of its hosting process; the service does not create its own thread and does not run in a carve up procedure unless you specify otherwise. You should run whatsoever blocking operations on a divide thread within the service to avoid Application Not Responding (ANR) errors.

Types of Services

These are the three different types of services:

Foreground

A foreground service performs some operation that is noticeable to the user. For example, an audio app would utilize a foreground service to play an sound track. Foreground services must brandish a Notification. Foreground services keep running even when the user isn't interacting with the app.

When you use a foreground service, you must display a notification then that users are actively aware that the service is running. This notification cannot be dismissed unless the service is either stopped or removed from the foreground.

Learn more nigh how to configure foreground services in your app.

Note: The WorkManager API offers a flexible way of scheduling tasks, and is able to run these jobs equally foreground services if needed. In many cases, using WorkManager is preferable to using foreground services directly.

Background
A background service performs an functioning that isn't directly noticed by the user. For instance, if an app used a service to compact its storage, that would normally be a background service.

Annotation: If your app targets API level 26 or college, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most situations, for example, y'all shouldn't admission location information from the background. Instead, schedule tasks using WorkManager.

Bound
A service is spring when an application component binds to information technology by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, ship requests, receive results, and fifty-fifty practice and so across processes with interprocess communication (IPC). A jump service runs only as long as another application component is bound to it. Multiple components can demark to the service at in one case, merely when all of them unbind, the service is destroyed.

Although this documentation more often than not discusses started and spring services separately, your service can work both means—it tin be started (to run indefinitely) and also allow binding. Information technology's merely a thing of whether y'all implement a couple of callback methods: onStartCommand() to allow components to starting time it and onBind() to allow binding.

Regardless of whether your service is started, spring, or both, any application component can employ the service (fifty-fifty from a separate awarding) in the same way that whatsoever component can use an action—past starting information technology with an Intent. Still, you lot can declare the service as private in the manifest file and block access from other applications. This is discussed more than in the section about Declaring the service in the manifest.

Choosing between a service and a thread

A service is simply a component that tin run in the groundwork, even when the user is not interacting with your awarding, and so yous should create a service just if that is what you lot need.

If y'all must perform work outside of your main thread, but only while the user is interacting with your application, you should instead create a new thread in the context of another application component. For example, if you want to play some music, but only while your activity is running, y'all might create a thread in onCreate(), start running it in onStart(), and end information technology in onStop(). Also consider using thread pools and executors from the java.util.concurrent parcel or Kotlin coroutines instead of the traditional Thread class. See the Threading on Android document for more information about moving execution to background threads.

Remember that if you practise use a service, information technology still runs in your application's main thread past default, so y'all should all the same create a new thread within the service if it performs intensive or blocking operations.

The basics

To create a service, y'all must create a bracket of Service or employ one of its existing subclasses. In your implementation, you must override some callback methods that handle cardinal aspects of the service lifecycle and provide a mechanism that allows the components to demark to the service, if appropriate. These are the virtually 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 groundwork indefinitely. If you implement this, it is your responsibleness to finish the service when its work is complete by calling stopSelf() or stopService(). If you merely want to provide binding, you don't need to implement this method.
onBind()
The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you lot must provide an interface that clients utilize to communicate with the service by returning an IBinder. Y'all must always implement this method; still, if y'all don't want to permit binding, you lot should return null.
onCreate()
The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand() or onBind()). If the service is already running, this method is non chosen.
onDestroy()
The organisation invokes this method when the service is no longer used and is existence destroyed. Your service should implement this to make clean up any resources such as threads, registered listeners, or receivers. This is the terminal call that the service receives.

If a component starts the service by calling startService() (which results in a telephone call to onStartCommand()), the service continues to run until it stops itself with stopSelf() or another component stops it past calling stopService().

If a component calls bindService() to create the service and onStartCommand() is not called, the service runs simply as long every bit the component is jump to it. Afterward the service is unbound from all of its clients, the system destroys it.

The Android organization stops a service only when retentivity is low and information technology must recover system resources for the action that has user focus. If the service is jump to an activity that has user focus, it's less probable to be killed; if the service is declared to run in the foreground, it's rarely killed. If the service is started and is long-running, the system lowers its position in the listing of background tasks over fourth dimension, and the service becomes highly susceptible to killing—if your service is started, you must design it to gracefully handle restarts by the system. If the organization kills your service, it restarts it as soon as resources get available, simply this also depends on the value that y'all return from onStartCommand(). For more information nigh when the system might destroy a service, see the Processes and Threading certificate.

In the post-obit sections, you lot'll run into how you tin create the startService() and bindService() service methods, also equally how to use them from other application components.

Declaring a service in the manifest

Yous must declare all services in your application'due south manifest file, just as you lot do for activities and other components.

To declare your service, add a <service> element every bit a child of the <application> element. Here is an example:

<manifest ... >   ...   <application ... >       <service android:proper name=".ExampleService" />       ...   </awarding> </manifest>        

See the <service> element reference for more data about declaring your service in the manifest.

At that place are other attributes that you can include in the <service> element to define backdrop such as the permissions that are required to kickoff the service and the procedure in which the service should run. The android:name attribute is the simply required aspect—it specifies the course proper name of the service. After you publish your awarding, go out this name unchanged to avoid the adventure of breaking code due to dependence on explicit intents to start or demark the service (read the blog post, Things That Cannot Change).

Circumspection: To ensure that your app is secure, always utilize 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 considering you cannot be certain of the service that responds to the intent, and the user cannot meet which service starts. Starting time with Android 5.0 (API level 21), the system throws an exception if you call bindService() with an implicit intent.

You can ensure that your service is bachelor to only your app by including the android:exported attribute and setting it to false. This effectively stops other apps from starting your service, even when using an explicit intent.

Note: Users tin see what services are running on their device. If they see a service that they don't recognize or trust, they can terminate the service. In social club to avoid having your service stopped accidentally by users, you need to add together the android:clarification attribute to the <service> chemical 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 another component starts by calling startService(), which results in a call to the service's onStartCommand() method.

When a service is started, it has a lifecycle that'due south independent of the component that started it. The service tin run in the groundwork indefinitely, even if the component that started it is destroyed. Every bit such, the service should finish itself when its chore is complete by calling stopSelf(), or another component tin stop it past calling stopService().

An awarding component such every bit an activity tin can showtime the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.

For example, suppose an action needs to relieve some information to an online database. The activity tin start a companion service and deliver it the data to relieve by 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 consummate, the service stops itself and is destroyed.

Caution: A service runs in the same procedure 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 application, the service slows downwardly activeness performance. To avoid impacting application performance, start a new thread within the service.

The Service course is the base class for all services. When you extend this class, it's important to create a new thread in which the service tin can complete all of its work; the service uses your awarding's main thread by default, which can tedious the performance of any action that your application is running.

The Android framework also provides the IntentService subclass of Service that uses a worker thread to handle all of the start requests, i at a time. Using this class is not recommended for new apps as information technology will not work well starting with Android 8 Oreo, due to the introduction of Background execution limits. Moreover, it's deprecated starting with Android 11. You tin can apply JobIntentService as a replacement for IntentService that is compatible with newer versions of Android.

The following sections draw how you can implement your own custom service, still y'all should strongly consider using WorkManager instead for most use cases. Consult the guide to background processing on Android to meet if there is a solution that fits your needs.

Extending the Service class

You can extend the Service course to handle each incoming intent. Hither's how a basic implementation might expect:

Kotlin

class HelloService : Service() {      private var serviceLooper: Looper? = null     individual var serviceHandler: ServiceHandler? = cypher      // Handler that receives messages from the thread     private inner class ServiceHandler(looper: Looper) : Handler(looper) {          override fun handleMessage(msg: Message) {             // Normally we would do some work here, similar download a file.             // For our sample, we merely sleep for 5 seconds.             endeavor {                 Thread.slumber(5000)             } take hold of (e: InterruptedException) {                 // Restore interrupt status.                 Thread.currentThread().interrupt()             }              // Stop the service using the startId, so that nosotros don't stop             // the service in the middle of handling another task             stopSelf(msg.arg1)         }     }      override fun onCreate() {         // Start upward the thread running the service.  Notation that we create a         // dissever thread considering the service usually runs in the process'southward         // main thread, which we don't desire to block.  We also make information technology         // background priority so CPU-intensive work will not disrupt our UI.         HandlerThread("ServiceStartArguments", Procedure.THREAD_PRIORITY_BACKGROUND).utilize {             start()              // Become the HandlerThread'southward Looper and utilize it 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, send a message to offset a job and deliver the         // starting time ID and so we know which asking we're stopping when we finish the job         serviceHandler?.obtainMessage()?.also { msg ->             msg.arg1 = startId             serviceHandler?.sendMessage(msg)         }          // If nosotros get killed, after returning from here, restart         return START_STICKY     }      override fun onBind(intent: Intent): IBinder? {         // We don't provide binding, and so return null         return null     }      override fun onDestroy() {         Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show()     } }            

Java

public class HelloService extends Service {   private Looper serviceLooper;   private ServiceHandler serviceHandler;    // Handler that receives messages from the thread   individual final class ServiceHandler extends Handler {       public ServiceHandler(Looper looper) {           super(looper);       }       @Override       public void handleMessage(Message msg) {           // Normally nosotros would do some work here, like download a file.           // For our sample, nosotros just slumber for 5 seconds.           try {               Thread.sleep(5000);           } catch (InterruptedException east) {               // Restore interrupt condition.               Thread.currentThread().interrupt();           }           // Cease the service using the startId, so that nosotros don't stop           // the service in the middle of treatment another job           stopSelf(msg.arg1);       }   }    @Override   public void onCreate() {     // Starting time upwardly the thread running the service. Note that we create a     // separate thread because the service normally runs in the process's     // main thread, which we don't desire to block. Nosotros also make it     // groundwork priority so CPU-intensive work doesn't disrupt our UI.     HandlerThread thread = new HandlerThread("ServiceStartArguments",             Process.THREAD_PRIORITY_BACKGROUND);     thread.get-go();      // Get the HandlerThread'southward Looper and apply 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 start request, send a message to start a chore and deliver the       // start ID then nosotros know which request we're stopping when we finish the job       Bulletin msg = serviceHandler.obtainMessage();       msg.arg1 = startId;       serviceHandler.sendMessage(msg);        // If nosotros become killed, afterward returning from hither, restart       return START_STICKY;   }    @Override   public IBinder onBind(Intent intent) {       // Nosotros don't provide binding, so return null       render null;   }    @Override   public void onDestroy() {     Toast.makeText(this, "service washed", Toast.LENGTH_SHORT).evidence();   } }            

The example code handles all incoming calls in onStartCommand() and posts the work to a Handler running on a background thread. It works just similar an IntentService and processes all requests serially, i after another. Y'all could change the code to run the piece of work on a thread puddle, for example, if you'd like to run multiple requests simultaneously.

Notice that the onStartCommand() method must return an integer. The integer is a value that describes how the organisation should continue the service in the event that the organization kills information technology. The return value from onStartCommand() must be one of the following constants:

START_NOT_STICKY
If the arrangement kills the service after onStartCommand() returns, do not recreate the service unless there are pending intents to deliver. This is the safest option to avert running your service when not necessary and when your awarding can merely restart whatsoever unfinished jobs.
START_STICKY
If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), just practise not redeliver the terminal intent. Instead, the system calls onStartCommand() with a null intent unless there are awaiting intents to start the service. In that case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands merely are running indefinitely and waiting for a chore.
START_REDELIVER_INTENT
If the system kills the service afterward onStartCommand() returns, recreate the service and call onStartCommand() with the last 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 virtually these return values, see the linked reference documentation for each constant.

Starting a service

You can commencement a service from an activeness or other awarding component past passing an Intent to startService() or startForegroundService(). The Android system calls the service's 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 background service, but the method signals to the organisation 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 can start the example service in the previous section (HelloService) using an explicit intent with startService(), as shown here:

Kotlin

Intent(this, HelloService::class.java).besides { intent ->     startService(intent) }            

Java

Intent intent = new Intent(this, HelloService.class); startService(intent);            

The startService() method returns immediately, and the Android system calls the service's onStartCommand() method. If the service isn't already running, the system first calls onCreate(), and so it calls onStartCommand().

If the service doesn't also provide bounden, the intent that is delivered with startService() is the just style of communication between the application component and the service. However, if yous want the service to ship a result back, the client that starts the service tin create a PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in the Intent that starts the service. The service can then use the broadcast to evangelize a consequence.

Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, but one request to end the service (with stopSelf() or stopService()) is required to stop information technology.

Stopping a service

A started service must manage its own lifecycle. That is, the arrangement doesn't cease or destroy the service unless it must recover organization retention and the service continues to run after onStartCommand() returns. The service must stop itself past calling stopSelf(), or another component can finish it past calling stopService().

One time requested to cease with stopSelf() or stopService(), the arrangement destroys the service as soon every bit possible.

If your service handles multiple requests to onStartCommand() concurrently, you shouldn't stop the service when you lot're washed processing a offset request, as you might have received a new commencement request (stopping at the end of the first request would finish the second 1). To avoid this problem, you can use stopSelf(int) to ensure that your asking to stop the service is always based on the nearly recent start request. That is, when you call stopSelf(int), you pass the ID of the kickoff asking (the startId delivered to onStartCommand()) to which your stop request corresponds. Then, if the service receives a new start request before yous are able to call stopSelf(int), the ID doesn't lucifer and the service doesn't stop.

Circumspection: To avoid wasting system resources and consuming bombardment power, ensure that your application stops its services when it'south done working. If necessary, other components can cease the service by calling stopService(). Fifty-fifty if you enable binding for the service, you must always terminate the service yourself if it ever receives a phone call to onStartCommand().

For more data well-nigh the lifecycle of a service, run across the section below near Managing the Lifecycle of a Service.

Creating a bound service

A bound service is ane that allows application components to demark to it by calling bindService() to create a long-standing connexion. Information technology by and large doesn't allow components to start it by calling startService().

Create a jump service when you want to interact with the service from activities and other components in your awarding or to betrayal some of your awarding'due south functionality to other applications through interprocess communication (IPC).

To create a jump service, implement the onBind() callback method to return an IBinder that defines the interface for advice with the service. Other application components can then telephone call bindService() to think the interface and begin calling methods on the service. The service lives merely to serve the application component that is jump to it, so when at that place are no components bound to the service, the organisation destroys it. Yous do not need to end a bound service in the same style 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 tin communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. After the client receives the IBinder, it can begin interacting with the service through that interface.

Multiple clients 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 organization 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 jump service discussion appears in a split document most Bound Services.

Sending notifications to the user

When a service is running, information technology tin notify the user of events using Toast Notifications or Condition Bar Notifications.

A toast notification is a message that appears on the surface of the current window for but a moment earlier disappearing. A status bar notification provides an icon in the status bar with a message, which the user can select in club to take an activeness (such equally start an action).

Usually, a status bar notification is the all-time technique to employ when background piece of work such as a file download has completed, and the user tin can now act on it. When the user selects the notification from the expanded view, the notification can first an activity (such as to display the downloaded file).

Run into the Toast Notifications or Status Bar Notifications programmer guides for more data.

Managing the lifecycle of a service

The lifecycle of a service is much simpler than that of an activity. However, it's fifty-fifty more of import that yous pay close attention to how your service is created and destroyed because a service can run in the groundwork without the user being enlightened.

The service lifecycle—from when information technology's created to when information technology's destroyed—can follow either of these ii paths:

  • A started service

    The service is created when some other component calls startService(). The service then runs indefinitely and must stop itself by calling stopSelf(). Another component can also stop the service past calling stopService(). When the service is stopped, the organisation destroys it.

  • A bound service

    The service is created when another component (a client) calls bindService(). The client then communicates with the service through an IBinder interface. The client can close the connexion past calling unbindService(). Multiple clients tin can bind to the same service and when all of them unbind, the organization destroys the service. The service does not demand to cease itself.

These two paths aren't entirely separate. You can bind to a service that is already started with startService(). For example, you can beginning a background music service by calling startService() with an Intent that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the electric current vocal, an activity can bind to the service by calling bindService(). In cases such as this, stopService() or stopSelf() doesn't actually stop the service until all of the clients unbind.

Implementing the lifecycle callbacks

Like an activity, a service has lifecycle callback methods that you tin implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods:

Kotlin

form ExampleService : Service() {     individual var startMode: Int = 0             // indicates how to behave if the service is killed     private var binder: IBinder? = null        // interface for clients that bind     individual var allowRebind: Boolean = false   // indicates whether onRebind should be used      override fun              onCreate() {         // The service is being created     }      override fun              onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {         // The service is starting, due to a call to startService()         render              startMode              }      override fun              onBind(intent: Intent): IBinder? {         // A client is binding to the service with bindService()         return              binder              }      override fun              onUnbind(intent: Intent): Boolean {         // All clients have unbound with unbindService()         return              allowRebind              }      override fun              onRebind(intent: Intent) {         // A client is binding to the service with bindService(),         // after onUnbind() has already been called     }      override fun              onDestroy() {         // The service is no longer used and is existence destroyed     } }            

Coffee

public form ExampleService extends Service {     int startMode;       // indicates how to bear if the service is killed     IBinder binder;      // interface for clients that bind     boolean allowRebind; // indicates whether onRebind should be used      @Override     public void              onCreate() {         // The service is being created     }     @Override     public int              onStartCommand(Intent intent, int flags, int startId) {         // The service is starting, due to a phone call to              startService()              return              startMode;     }     @Override     public IBinder              onBind(Intent intent) {         // A customer is binding to the service with              bindService()              return              binder;     }     @Override     public boolean              onUnbind(Intent intent) {         // All clients have unbound with              unbindService()              return              allowRebind;     }     @Override     public void              onRebind(Intent intent) {         // A client is binding to the service with              bindService(),         // after onUnbind() has already been chosen     }     @Override     public void              onDestroy() {         // The service is no longer used and is being destroyed     } }            

Note: Unlike the activity lifecycle callback methods, yous are non required to 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().

Effigy ii illustrates the typical callback methods for a service. Although the figure separates services that are created by startService() from those created by bindService(), keep in mind that whatever service, no thing how it's started, tin potentially allow clients to bind to it. A service that was initially started with onStartCommand() (by a customer calling startService()) tin yet receive a telephone call to onBind() (when a client calls bindService()).

By implementing these methods, you tin monitor these two nested loops of the service's lifecycle:

  • The entire lifetime of a service occurs between the fourth dimension that onCreate() is called and the fourth dimension that onDestroy() returns. Similar an action, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy(). For example, a music playback service can create the thread where the music is played in onCreate(), and and so it tin can stop the thread in onDestroy().

    Note: The onCreate() and onDestroy() methods are called for all services, whether they're created by startService() or bindService().

  • The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method is handed the Intent that was passed to either startService() or bindService().

    If the service is started, the agile lifetime ends at the same time that the entire lifetime ends (the service is even so agile even after onStartCommand() returns). If the service is jump, the active lifetime ends when onUnbind() returns.

Note: Although a started service is stopped past a phone call to either stopSelf() or stopService(), there isn't a corresponding callback for the service (there's no onStop() callback). Unless the service is bound to a customer, the system destroys it when the service is stopped—onDestroy() is the only callback received.

For more information about creating a service that provides binding, come across the Bound Services certificate, which includes more information well-nigh the onRebind() callback method in the section about Managing the lifecycle of a bound service.

How To Access Running Service New Android Update,

Source: https://developer.android.com/guide/components/services

Posted by: elzyowestrim.blogspot.com

0 Response to "How To Access Running Service New Android Update"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel