| 1 | <service android:name=".HelloService" /> |
radimkliment / Service
Last active 4 months ago
Implementation of service, bounded service in Android
Revision 9714b20030601c483a724bc7089bf49e8fe5e078
| 1 | class 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 | } |
| 1 | class 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 | } |
| 1 | // without bound |
| 2 | override fun onStart() { |
| 3 | super.onStart() |
| 4 | val intent = Intent(this, HelloService::class.java) |
| 5 | startService(intent) |
| 6 | } |
| 7 | |
| 8 | // with bound |
| 9 | private lateinit var mService: LocalService |
| 10 | private var mBound: Boolean = false |
| 11 | |
| 12 | /** Defines callbacks for service binding, passed to bindService(). */ |
| 13 | private 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 | |
| 27 | override 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 | |
| 35 | override fun onStop() { |
| 36 | super.onStop() |
| 37 | unbindService(connection) |
| 38 | mBound = false |
| 39 | } |