туториалу не запускается. bindService возвращает false
AndroidManifest.xml
<application ...>
<service android:name=".MyBinderService" />
</application>
MyBinderService.kt
class MyBinderService : Service() {
private val binder = LocalBinder()
private val mGenerator = Random
val randomNumber: Int
get() = mGenerator.nextInt(100)
inner class LocalBinder : Binder() {
fun getService(): MyBinderService = this@MyBinderService
}
override fun onBind(intent: Intent?): IBinder {
return binder
}
}
Activity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binderService: MyBinderService
private var bound = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as MyBinderService.LocalBinder
binderService = binder.getService()
bound = true
}
override fun onServiceDisconnected(name: ComponentName?) {
bound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
...
// Binder Service
startServiceButton.setOnClickListener {
Intent(this, MyBinderService.LocalBinder::class.java).also { intent ->
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
stopServiceButton.setOnClickListener {
unbindService(connection)
bound = false
}
findViewById<Button>(R.id.button4).setOnClickListener {
if (bound) {
binderService.randomNumber
}
}
}
}
Да, сработало, спасибо. Не обратил внимание
Обсуждают сегодня