-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoundServiceExample
48 lines (41 loc) · 1.24 KB
/
BoundServiceExample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//in Service.kt
private val localBinder = LocalBinder()
class service.kt{
override fun onBind(p0: Intent?): IBinder? {
return localBinder
}
//BinderClass at the end of service.kt
inner class LocalBinder:Binder(){
fun getBindServiceInstance():SwipeService{
return this@SwipeService
}
}
}
//in MainActivity.kt
private var mBound: Boolean = false
class MainActivity.kt{
//BinderClassIntialization
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
mBound = true
val localBinder = p1 as SwipeService.LocalBinder
swipeService = localBinder.getBindServiceInstance()
}
override fun onServiceDisconnected(p0: ComponentName?) {
mBound = false
}
}
override fun onStart() {
super.onStart()
val intent = Intent(this, SwipeService::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
Unbind from the service
if (mBound) {
unbindService(serviceConnection)
mBound = false
}
}
}