探究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()
    }
}
  • 启动和停止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绑定!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值