Declaring your service

To declare your service, you need to add its class to the Android Manifest. The following code snippet explains what the service definition in Android Manifest should look like:

    <manifest xmlns:android=
"http://schemas.android.com/apk/res/android"

package="com.journaler"> ... <application ... > <service android:name=".service.MainService" android:exported="false" /> ... </application>
</manifest>

As you can see, we defined the MainService class that extends the Service class and it's located under the service package. The exported flag is set to false, which means that the service will run in the same process as our application. To run your  service in a separate process, set this flag to true.

It's important to note that the Service class is not the only one you can extend. The IntentService class is also available. So, what do we get when we extend it? IntentService represents a class derived from the Service class. IntentService uses the worker thread to process requests one by one. We must implement the onHandleIntent() method for that purpose. This is what it looks like when the IntentService class is extended:

     public class MainIntentService extends IntentService { 
       /** 
       * A constructor is mandatory! 
       */ 
       public MainIntentService() { 
         super("MainIntentService"); 
       } 
 
       /** 
       * All important work is performed here. 
       */ 
       @Override 
       protected void onHandleIntent(Intent intent) { 
         // Your implementation for handling received intents. 
   
       } 
}

Let's go back on extending the Service class and focus on it. We will override onStartCommand() method to look like this:

    override fun onStartCommand(intent: Intent?, flags: Int, startId:  
Int): Int { return Service.START_STICKY }

So, what does the START_STICKY return result mean? If it happens that our service is killed by the system, or we kill the application to which the service belongs, it will start again. Opposite of this is START_NOT_STICKY; in that case, the service will not be recreated and restarted.