Forked from RohitSurwase/CoroutineIntentService.kt
Created
November 18, 2021 04:49
-
-
Save quangquy87/9a2334186411d33af2be012f989edf7c to your computer and use it in GitHub Desktop.
IntentService (Service) using Kotlin Coroutines instead of Handler+Looper.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Service | |
import android.content.Intent | |
import android.os.IBinder | |
import android.support.annotation.Nullable | |
import android.support.annotation.WorkerThread | |
import kotlinx.coroutines.* | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.channels.SendChannel | |
import kotlinx.coroutines.channels.actor | |
import kotlin.coroutines.CoroutineContext | |
abstract class CoroutineIntentService(private val mName: String) : Service(), CoroutineScope { | |
private var coroutineJob: Job = Job() | |
override val coroutineContext: CoroutineContext | |
get() = Dispatchers.IO + coroutineJob | |
private var mRedelivery: Boolean = false | |
private lateinit var handlerActor: SendChannel<ActorMessage> | |
fun setIntentRedelivery(enabled: Boolean) { | |
mRedelivery = enabled | |
} | |
override fun onCreate() { | |
super.onCreate() | |
handlerActor = handlerActor(mName) | |
} | |
override fun onStartCommand(@Nullable intent: Intent?, flags: Int, startId: Int): Int { | |
runBlocking { | |
val msg = ActorMessage() | |
msg.arg1 = startId | |
msg.obj = intent | |
intent?.let { handlerActor.send(msg) } | |
} | |
return if (mRedelivery) Service.START_REDELIVER_INTENT else Service.START_NOT_STICKY | |
} | |
override fun onDestroy() { | |
coroutineJob.cancel() | |
} | |
@Nullable | |
override fun onBind(intent: Intent): IBinder? { | |
return null | |
} | |
@WorkerThread | |
protected abstract fun onHandleIntent(@Nullable intent: Intent?) | |
private fun CoroutineScope.handlerActor(mName: String) = actor<ActorMessage>( | |
context = coroutineJob + CoroutineName(mName), | |
capacity = Channel.UNLIMITED, | |
start = CoroutineStart.LAZY | |
) { | |
for (msg in channel) { | |
onHandleIntent(msg.obj as Intent) | |
stopSelf(msg.arg1) | |
} | |
} | |
} | |
data class ActorMessage(var what: Int = 0, var arg1: Int = 0, var obj: Any? = null) | |
/** | |
* CoroutineIntentService usage example | |
* | |
* class MyCoroutineIntentServiceImpl : CoroutineIntentService("MyCoroutineIntentServiceImpl") { | |
* override fun onHandleIntent(intent: Intent?) { | |
* //Handle your intent | |
* } | |
* } | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment