Pro Android with Kotlin



Yüklə 4,6 Kb.
Pdf görüntüsü
səhifə44/231
tarix29.11.2023
ölçüsü4,6 Kb.
#138831
1   ...   40   41   42   43   44   45   46   47   ...   231
@de android telegram Pro Android with Kotlin Developing Modern Mobile

34
CHAPTER 4: Services
class MyService : Service() {
// Binder given to clients
private val binder: IBinder = MyBinder(this)
// Random number generator
private val generator: Random = Random()
override
fun onBind(intent: Intent):IBinder {
return binder
}
/** method for clients */
fun getRandomNumber():Int {
return generator.nextInt(100)
}
}
To bind to this service internally, from the same app, inside the service using the client, write 
the following:
val servcConn = object : ServiceConnection {
override
fun onServiceDisconnected(compName: ComponentName?) {
Log.e("LOG","onServiceDisconnected: " + compName)
}
override
fun onServiceConnected(compName: ComponentName?,
binder: IBinder?) {
Log.e("LOG","onServiceConnected: " + compName)
val servc = (binder as MyBinder).getService()
Log.i("LOG", "Next random number from service: " +
servc.getRandomNumber())
}
override
fun onBindingDied(compName:ComponentName) {
Log.e("LOG","onBindingDied: " + compName)
}
}
val intent = Intent(this, MyService::class.java)
val flags = BIND_AUTO_CREATE
bindService(intent, servcConn, flags)
Here, the 
object: ServiceConnection {...}
construct is the Kotlin way of implementing an 
interface by creating an object of an anonymous inner class, like 
new ServiceConnection()
{...}
in Java. The construct is called an 
object expression
in Kotlin. The 
this
inside the 
intent constructor in this case refers to a 
Context
object. You can use it like this inside an 
activity. If you have the 
Context
in a variable instead, use that variable’s name here.
Of course, instead of the logging, you should do more meaningful things. Especially inside 
the 
onSeviceConnected()
method you can save the binder or service in a variable for further 
use. Just make sure, having said all that, that you appropriately react to a died binding or a 
killed service connection. You could, for example, try to bind the service again, tell the user, 
or both.



Yüklə 4,6 Kb.

Dostları ilə paylaş:
1   ...   40   41   42   43   44   45   46   47   ...   231




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə