Service 的基本用法
开始学习四大组件之一的Service
定义一个Service
定义一个类继承Service
class MyService : Service() {
override fun onCreate() {//创建时调用
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {//启动时调用
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {//销毁调用
super.onDestroy()
}
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
}
重写一些常用方法
启动和停止Service
启动和停止Service非常简单
binding.startServiceBtn.setOnClickListener {
val intent = Intent(this,MyService::class.java)
startService(intent)
}
binding.stopServiceBtn.setOnClickListener {
val intent = Intent(this,MyService::class.java)
stopService(intent)
}
只需要定义一个Intent然后调用startService/stopService方法即可。
Activity和Service进行通信
调用onBind可以进行通信。
现在我们要实现一个功能;在MyService提供一个下载功能,在Activity中指挥Sevice开始下载,以及随时查看下载进度。
private val mBinder = DownloadBinder()
class DownloadBinder : Binder(){
fun startDownload(){
Log.d("MyService","startDownload executed")
}
fun getProgress():Int{
Log.d("MyService","getProgress executed")
return 0
}
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
首先新建了一个DownloadBinder类继承自Binder,类里简单实现两个方法,一个是开始下载,另一个是查看进度,然后再onBind中返回这个类
在MainActivity中修改代码
class MainActivity : AppCompatActivity() {
lateinit var downloadBinder: MyService.DownloadBinder
private val connection = object : ServiceConnection{
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
downloadBinder = service as MyService.DownloadBinder
downloadBinder.startDownload()
downloadBinder.getProgress()
}
override fun onServiceDisconnected(name: ComponentName?) {
TODO("Not yet implemented")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
...
binding.bindServiceBtn.setOnClickListener {
val intent = Intent(this,MyService::class.java)
bindService(intent,connection,Context.BIND_AUTO_CREATE)
}
binding.unbindServiceBtn.setOnClickListener {
unbindService(connection)
}
}
}
这里首先创建了一个ServiceConnection的匿名类,并且在里面重写了onServiceConnected()方法和onServiceDisconnected()方法。
onServiceConnected()方法会在Activity与Service绑定成功时调用,onServiceDisconnected()则会在绑定接触时调用(因为一般用不到所以不写具体内容)。
那么在onServiceConnected()中,我们先获得一个DownloadBinder的实例,然后在调用方法。
点击事件的实现则更加简单
建立绑定依旧是使用Intent,调用bindService接收三个参数,第一个是Intent对象,第二个是前面创建出的ServiceConnection实例,第三个是flag,这里的BIND_AUTO_CREATE是指绑定后自动创建Service。(这会使得onStartCommand不会执行)