普通的Service
class NormalService: Service() {
override fun onCreate() {
logger("onCreate")
super.onCreate()
}
override fun onBind(intent: Intent?): IBinder? {
logger("onBind")
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
logger("onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
logger("onDestroy")
super.onDestroy()
}
private fun logger(str: String) {
Log.d(javaClass.name, str)
}
}
调用startService
onCreate
onStartCommand
多次调用 startService
,onStartCommand
会被多次调用
调用stopService
onDestroy
用于和activity绑定交互的Service
创建service
class BindService: Service() {
inner class MyBinder: Binder() {
fun getService(): BindService {
return this@BindService
}
}
val myBinder = MyBinder()
override fun onBind(intent: Intent?): IBinder? {
logger("onBind")
return myBinder
}
override fun onUnbind(intent: Intent?): Boolean {
logger("onUnbind")
return super.onUnbind(intent)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
logger("onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
logger("onDestroy")
super.onDestroy()
}
private fun logger(str: String) {
Log.d(javaClass.name, str)
}
}
创建ServiceConnection 并且bind
val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
logger("onServiceConnected")
}
override fun onServiceDisconnected(name: ComponentName?) {
logger("onServiceDisconnected")
}
}
bindService(bIntent, serviceConnection, BIND_AUTO_CREATE)
调用bindService
onCreate
onBind
onServiceConnected
多次调用bindService
无效果,不会多次绑定
调用 unBindService
- onUnbind
- onDestroy
如果不调用unBindService
而直接调用stopService
没效果,服务并不会停止。
所有的service必须在AndroidManifest.xml中注册才能使用。