Last active 4 hours ago

Implementation of service, bounded service in Android

Revision bcafa857e1d331121da8e16e84ebfed6d12a419e

AndroidManifest.xml Raw
1<service android:name=".HelloService" />
BoundedHelloService.kt Raw
1class BoundedHelloService : Service() {
2 private val binder = LocalBinder()
3
4 inner class LocalBinder : Binder() {
5 fun getService(): HelloService = this@HelloService
6 }
7
8 private val mGenerator = Random()
9
10 val randomNumber: Int get() = mGenerator.nextInt(100)
11
12 /** Method for clients. */
13 val randomNumber: Int
14 get() = mGenerator.nextInt(100)
15
16 override fun onBind(intent: Intent): IBinder {
17 return binder
18 }
19
20 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
21 return START_STICKY
22 }
23
24}
HelloService.kt Raw
1class HelloService : Service() {
2 override fun onBind(p0: Intent?): IBinder? {
3 return null
4 }
5
6 /*
7 START_NOT_STICKY
8 START_STICKY
9 START_REDELIVER_INTENT
10 */
11 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
12 return START_STICKY
13 }
14
15}
MyActivity.kt Raw
1// without bound
2override fun onStart() {
3 super.onStart()
4 val intent = Intent(this, HelloService::class.java)
5 startService(intent)
6}
7
8// with bound
9private lateinit var mService: LocalService
10private var mBound: Boolean = false
11
12/** Defines callbacks for service binding, passed to bindService(). */
13private val connection = object : ServiceConnection {
14
15 override fun onServiceConnected(className: ComponentName, service: IBinder) {
16 // We've bound to LocalService, cast the IBinder and get LocalService instance.
17 val binder = service as LocalService.LocalBinder
18 mService = binder.getService()
19 mBound = true
20 }
21
22 override fun onServiceDisconnected(arg0: ComponentName) {
23 mBound = false
24 }
25}
26
27override fun onStart() {
28 super.onStart()
29 // Bind to LocalService.
30 Intent(this, LocalService::class.java).also { intent ->
31 bindService(intent, connection, Context.BIND_AUTO_CREATE)
32 }
33}
34
35override fun onStop() {
36 super.onStop()
37 unbindService(connection)
38 mBound = false
39}