IntentService and JobIntentService
First, let’s create IntentService and then migrate to JobIntentService.
In Android 11 IntentService is deprecated.
Create from template IntentService:
In AndroidManifest.xml this code will be generated:
The MyIntentService.kt class should look like this:
In MainActivity.kt we will setOnClickListener on button and launch startActionFoo(…) static function:
Logcat output would look like this:
Now, let's migrate from IntentService to JobIntentService.
Change AndroidManifest.xml code:
MainActivity.kt class will stay the same.
In MyIntentService.kt do the following changes:
The Logcat result will be the same.
Send results from JobIntentService to the UI
Let's send data from JobIntentService to TextView by clicking the Button.
First, create inner class MyResultReceiver(…), and pass it as a parameter to static function, which will start the service.
MainActivity.kt class code change:
In startActionFoo() function, we get receiver, put it into intent and start service.
In onHandleWork(…) we create Bundle, put required data there, and using receiver send it to UI.
Change MyIntentService.kt class's code:
Layout: When Button will be clicked, the text on TextView will be equal to the received text e.g. "param1"