Last active 4 hours ago

Implementation of service, bounded service in Android

Revision a8f179cba6f28bcde043331a709b1434c8486cab

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