

However, since you won’t be restarted by the system automatically, it is usually not a useful method for indefinite or very long-running tasks. This is a good option if you want full control of when your Service is started. START_NOT_STICKY basically means you don’t want your Service restarted by the system. Which of these you return determines if and how your Service will be restarted if you app gets killed by the system. The method also returns an int that can be one of the following three (I’m not including the compatibility constants): START_NOT_STICKY, START_STICKY and START_REDELIVER_INTENT. When a Service is started, it triggers a call to onStartCommand() with three parameters an Intent (which can be null, more on this in a moment), an int containing the flags for this start request, and another int defining the ID for this start request. This is to prevent apps from running in the background without notifying the user, since Service.startForeground() requires a Notification that will be displayed (more on this later in this post). When you use this new method, you must also call Service.startForeground() within the same amount of time as you would get an ANR if you would block the main thread.

This is usually the case when you want to start a Service from a BroadcastReceiver or some other event that was triggered when your app isn’t running in the foreground. From that version you can no longer call Context.startService() unless your application is in the foreground. The difference between this and the old one is due to a change in when an app can start a Service that was introduced in API level 26. From the client side, interacting with a Service by starting it is really not more complicated than this.įrom API level 26, we also got the method Context.startForegroundService(). The code above is probably something you have written before a few times. StartServiceIntent.putExtra(EXTRA_DEVICE_UUID, deviceUuid) val startServiceIntent = Intent(context, MyService::class.java) We create an Intent targeting the Service, and we can pass additional parameters as extras.

While binding involves a more complex chain of asynchronously receiving a IBinder object and invoking methods on it in an RPC style, starting is more of a fire-and-forget approach. The most common way we interact with a Service today is usually by calling startService() and passing it an Intent. In this post we will look at the other way of interacting with a Service, namely starting and stopping. In my previous post I covered how binding to a Service worked. 8 min read TL DR: This is how your onStartCommand() probably should look like.
