使用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()
}
}
-
启动和停止Service
在 MainActivity 中启动
startServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
startService(intent)
}
stopServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
stopService(intent)
}
-
Activity和Service进行通信
实现通信的思路是通过创建一个 Binder对象来进行通信。比如想完成一个Activity中对Service的下载功能进行管理。在MyService中添加一个Binder对象,代码如下:
class MyService : Service() {
private val mBinder = DownloadBinder()
class DownloadBinder : Binder() {
fun startDownload() {
Log.d("MyService", "startDownload executed")
}
fun getProcess(): Int {
Log.d("MyService", "getProcess executed")
return 0
}
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
......
}
创建好了Binder对象,需要Activity与之绑定。
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.getProcess()
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
......
bindServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
unbindServiceBtn.setOnClickListener {
unbindService(connection)
}
}
}
先创建了一个ServiceConnection的匿名类实现,并重写了 onServiceConnected() 方法和 onServiceDisconnected() 方法。onServiceConnected() 会在 Activity 与 Service 绑定时调用。在onServiceConnected 中我们获取了DownloadBinder的实例,就可以调用其中的方法进行对Service的控制!!
MyService 可以和任何 Activity绑定!