Activity和Service进行通信

2021-07-13  本文已影响0人  别看后面有人

之前说了activity对sevice的启动,但是启动之后的service做了什么,这时需要onBind()方法
以下载为例代码如下

class MyService : Service() {

    val TAG="MyService"
    private val mBinder=DownloadBinder()

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate: ")
    }
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
        Log.d(TAG, "onBind: ")
        return mBinder
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand: ")
        return super.onStartCommand(intent, flags, startId)

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: ")
    }

    class DownloadBinder:Binder(){
        val TAG="DownloadBinder"
        fun startDownload(){
            Log.d(TAG, "startDownload: ")
        }

        fun getProgress():Int{
            Log.d(TAG, "getProgress: ")
            return 0
        }
    }
}

activity中的调用:

 lateinit var downloadBinder: MyService.DownloadBinder
    private val connection=object :ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
            TODO("Not yet implemented")
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
           downloadBinder=service as MyService.DownloadBinder
            downloadBinder.startDownload()
            downloadBinder.getProgress()
        }
    }

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        bindServiceBtn.setOnClickListener {
            val intent=Intent(this,MyService::class.java)
            bindService(intent,connection,Context.BIND_AUTO_CREATE)
        }

        unBindServiceBtn.setOnClickListener {
            unbindService(connection)
        }
}

上一篇 下一篇

猜你喜欢

热点阅读