讲实话,看完Service没有太大的感觉,感觉还是没有什么实际的场景,工作中使用service的场景也比较少,先记录一下基本的使用方法吧。后面如果有比较有意思的关于Service问题,再到这里记录
基本使用
class MyService : Service() {
val TAG = "MasterLi@Myservice"
override fun onBind(intent: Intent): IBinder {
//TODO
}
//第一次创建Service的时候调用.如果多次启动,只会调用一次onCreate
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate: ")
}
//启动Service的时候调用,每次启动都会调用
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartCommand: ")
return super.onStartCommand(intent, flags, startId)
}
//销毁Service的时候调用
override fun onDestroy() {
Log.d(TAG, "onDestroy: ")
super.onDestroy()
}
}
val intent = Intent(this, MyService::class.java)
mButtonStart.setOnClickListener {
startService(intent)
}
mButtonStop.setOnClickListener {
stopService(intent)
}
Service和Activity绑定
lateinit var dowLoaderBinder: MyService.DownLoadBinder
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
dowLoaderBinder = service as MyService.DownLoadBinder
dowLoaderBinder.startDownLoad()
Log.d(TAG, "onServiceConnected: ${dowLoaderBinder.getProgress()}")
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.d(TAG, "onServiceDisconnected: ")
}
}
val intent = Intent(this, MyService::class.java)
//其中Context.BIND_AUTO_CREATE,表示当Activity和Service绑定的时候自动创建service
mButtonBind.setOnClickListener {
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
mButtonUnbind.setOnClickListener {
unbindService(connection)
}
class MyService : Service() {
val TAG = "MasterLi@Myservice"
private val mBinder = DownLoadBinder()
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate: ")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartCommand: ")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
Log.d(TAG, "onDestroy: ")
super.onDestroy()
}
class DownLoadBinder() : Binder() {
private var process = 0
fun startDownLoad () {
Log.d("MasterLi@DownLoadBinder", "startDownLoad")
process += 1
}
fun getProgress(): Int {
return process
}
}
}
使用IntentService
Service默认都是在主线程中运行的,IntentService的出现就是为了防止在主线程中执行耗时操作。
class MyServiceIntent : IntentService("MyServiceIntent") {
override fun onHandleIntent(intent: Intent?) {
Log.d("MasterLi", "onHandleIntent: ")
}
override fun onDestroy() {
super.onDestroy()
Log.d("MasterLi", "onDestroy: ")
}
}
其中onHandleIntent函数就是在子线程中执行的,其他的似乎和普通的Service没有其他区别
生命周期
Service的生命周期没有像Activity那么负责。我看完感觉主要有如下几个点需要注意的:
- 每个Service只会存在一个示例,只需调用一次stopService或stopSelf即可
- 如果一个Service被绑定同时被启动,需要在unbindService和stopService之后才会执行onDestory
到这里似乎关于Service的所有东西都结束了,但是还是感觉什么都没学到。在创建IntentService的时候,发现android sutdio可以直接创建IntentService,但是里面没看懂是要做什么,后面有工作场景的时候,再好好研究一下吧