声明 : 在工作中经常会遇到两个App之间通信的问题,ALDL作为Android官方推荐的进程间通信工具,此篇博文,仅仅用来记录如何使用ALDL实现通信
1.服务端App
- 首先需要编写ALDL文件(与java文件在同一级),右键新建如下图:
aldl :
package com.hopechart.musicplayer;
interface ITest {
void test();
String greet(String someone);
}
写完aldl文件之后 点击 Make Project ,编译器会生成对应的ITest.java文件
- 写一个Service,用于绑定
package com.hopechart.musicplayer;
public class MyService extends Service {
private static final HQAPI hqApi = HQAPI.getHQAPI();
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
}
ITest.Stub stub = new ITest.Stub() {
@Override
public void test() throws RemoteException {
Log.e("MyServiceTest", "test");
}
@Override
public String greet(String someone) throws RemoteException {
Log.e("MyServiceTest", "greet");
return "hello, " + someone;
}
};
@Override
public IBinder onBind(Intent intent) {
Log.e("MyServiceTest", "onBind");
return stub;
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("MyServiceTest", "onUnbind");
return true;
}
}
在AndroidMainifest中注册
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.hopechart.musicplayer.MyService" />
</intent-filter>
</service>
2. 客户端Service
private lateinit var iTest: ITest
private var isBindSuccess = false
override fun onClick(v: View?) {
when (v?.id) {
R.id.bindService -> {
var serviceIntent = Intent()
serviceIntent.setPackage("com.hopechart.musicplayer")
serviceIntent.action = "com.hopechart.musicplayer.MyService"
bindService(serviceIntent, object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.e("testService","service连接成功")
this@MainActivity.iTest = ITest.Stub.asInterface(service)
isBindSuccess = true
}
},Context.BIND_AUTO_CREATE)
}
R.id.testAldl -> {
if (isBindSuccess) {
iTest.test()
try {
val helloNba= iTest.greet("KD")
Toast.makeText(this, helloNba, Toast.LENGTH_SHORT).show()
} catch (e: RemoteException) {
e.printStackTrace()
}
}
}
}
}
如果界面弹出hello + 自定传入的参数,即绑定成功 如果哪步有问题,欢迎评论区留言,一起解决
|