package com.ehome.kotlin.bindservice
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleScope.launch{
getSampleService().test()
}
}
suspend fun getSampleService():SampleService {
return suspendCoroutine { continuation ->
val intent = Intent(this, SampleService::class.java)
bindService(intent, object : ServiceConnection {
var sampleService: SampleService ? = null
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val sampleBinder = service as SampleService.SampleBinder
sampleService = sampleBinder.sampleService
continuation.resume(sampleService!!)
}
override fun onServiceDisconnected(name: ComponentName?) {
continuation.resume(sampleService!!)
}
},BIND_AUTO_CREATE)
}
}
}