Pro Android with Kotlin



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

33
CHAPTER 4: Services
The second case is given if the service we want to start is part of another app and thus is an 
external
service. You then have to add an intent filter inside the service declaration. Here’s an 
example:
android:name=".MyService"
android:enabled="true"
android:exported="true">




In this example, 
is the name of app’s package, and instead of 
START_SERVICE

you can write a different identifier if you like. Now, inside the service client, you can write the 
following to start and stop the external service, where inside the intent constructor you have 
to write the same string as in the intent filter declaration of the service:
val intent = Intent("
.START_SERVICE")
intent.setPackage("
")
startService(intent)
// ... do something ...
stopService(intent)
The 
setPackage()
statement is important here (of course you have to substitute the service’s 
package name); otherwise, a security restriction applies, and you get an error message.
Binding to Services
Starting a service is one part of the story. The other part is using them while they are 
running. This is what the 
binding
of services is used for.
To create a service that can be bound to or from the same app, write something like this:
/**
* Class used for binding locally, i.e. in the same App.
*/
class MyBinder(val servc:MyService) : Binder() {
fun getService():MyService {
return servc
}
}
Note
Since intents allow general-purpose extra attributes by using one of the various 
putExtra()
methods, we can also pass data to the service.



Yüklə 4,6 Kb.

Dostları ilə paylaş:
1   ...   39   40   41   42   43   44   45   46   ...   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ə