一.服务端
1.创建aidl文件,然后记得build下生成java文件
package com.example.aidlservice31;
// Declare any non-default types here with import statements
interface IMyAidlServer {
// 接收一个字符串参数
void setData(String value);
// 返回一个字符串
String getData();
}
2.创建远程MyService.class
class MyService : Service() {
private val mBinder by lazy { MyBinder() }
override fun onBind(intent: Intent): IBinder {
return mBinder
}
inner class MyBinder : IMyAidlServer.Stub() {
private var mData: String = "李小龙"
override fun setData(value: String) {
Log.e("yjj", "客户端发来的数据== $value")
mData = value
}
override fun getData() = mData+"返回的数据"
}
}
3.在AndroidManifest配置MyService
<service
android:name=".MyService"
//远程可访问
android:exported="true"
//开启远端进程
android:process=":remote">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
//客户端通过action绑定MyService
<action android:name="com.example.aidlservice31.MyService" />
</intent-filter>
</service>
二、客户端
1.复制服务端aidl文件夹,啥也别改,然后build下,自动生成java文件。
2.绑定服务,传输数据
class MainActivity : AppCompatActivity() {
private var mServer: IMyAidlServer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initView()
}
private var mNumber = 0
private fun initView() {
val tvGetDataValue: TextView = findViewById(R.id.tvGetDataValue)
//绑定服务器
findViewById<TextView>(R.id.tvBindService).setOnClickListener {
setConnection()
}
//传递数据给服务端
findViewById<TextView>(R.id.tvSetData).setOnClickListener {
mNumber++
mServer?.data = mNumber.toString()
Log.e("yjj", "setData == " + mServer?.data)
}
//获取服务端数据
findViewById<TextView>(R.id.tvGetData).setOnClickListener {
Log.e("yjj", "getData == " + mServer?.data)
mServer?.data.let {
tvGetDataValue.text = it
}
Toast.makeText(this,tvGetDataValue.text,Toast.LENGTH_LONG).show()
}
}
private val mMyServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, remoteService: IBinder?) {
Log.e("yjj", "绑定远程服务成功!")
mServer = IMyAidlServer.Stub.asInterface(remoteService)
}
override fun onServiceDisconnected(name: ComponentName?) {
mServer = null
}
}
private fun setConnection() {
try {
val intent = Intent()
// AIDLServer 项目的包名(applicationId)
// AIDLServer 项目中注册的服务的全路径
intent.component =
ComponentName("com.example.aidlservice31", "com.example.aidlservice31.MyService")
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
var issuccess = bindService(intent, mMyServiceConnection, Context.BIND_AUTO_CREATE)
Log.e("yjj", "开始绑定服务器issuccess=$issuccess")
} catch (e: SecurityException) {
e.printStackTrace()
}
}
override fun onDestroy() {
super.onDestroy()
unbindService(mMyServiceConnection)
}
}
好像有些手机是不行的,比如华为荣耀v30。不行的话,换个手机试试吧。