安卓service使用(二)

2021-07-16  本文已影响0人  motosheep

前文回顾:service基本使用(一)
本次文章介绍,主要是远程service的使用,先附上代码链接:代码下载
代码结构图:

代码结构
如图。aidl文件夹定义了一个RemoteListener.aidl,一个RemoteIPCBinder.aidl。前者用于作为服务绑定的binder,后者作为监听对象。

注意事项:

(1)对于startService()和stopService()的使用,注意由于实际使用项目的不同,去决定采取隐式or显式的调用。
(2)对于bindService(),注意断开连接时的重连。注意连接成功时的binder对象初始化。核心代码如下:

        findViewById<Button>(R.id.bind_service).setOnClickListener {
            mConnection = object : ServiceConnection {
                override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
                    try{
                        mBinder = RemoteIPCBinder.Stub.asInterface(p1)
                        mBinder?.connect("client 1 connect")
                        mBinder?.setOnListener(mListener)
                    }catch (e:Exception){
                        KtLogUtil.d("onServiceConnected error:${e.message}")
                    }
                }

                override fun onServiceDisconnected(p0: ComponentName?) {
                    mBinder?.removeListener(mListener)
                }
            }
            //绑定service
            val serviceIntent = Intent(this, RemoteService::class.java)
            bindService(serviceIntent, mConnection!!, BIND_AUTO_CREATE)
        }

(3)注意aidl中,in,out,input三者的区别以及用法
that's all------------------------------------------------------------------------------------------------------------------------

上一篇 下一篇

猜你喜欢

热点阅读