AIDL android interface definition language 也就是android接口定义语言.是用于定义服务器和客户端通信接口的一种描述语言,可拿来生成用于IPC,实现app间跨进程通讯.
然后在项目里创建aidl (app->new->AIDL->AIDL File)
创建的aidl文件会有个默认接口不想要就直接删掉
// ITestaidl.aidl
package com.t2mobile.test1;
// Declare any non-default types here with import statements
interface ITestaidl {
int getAge();
}
然后在AndroidStudio的build里 Make Project(编译器会生成对应的Binder文件)
接着创建一个service
package com.t2mobile.test1;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return my_binder;
}
private IBinder my_binder = new ITestaidl.Stub() {
@Override
public int getAge() throws RemoteException {
return 666;
}
};
}
AndroidManifest.xml里给自己创建的MyService定义一个action,服务端应用就算完成了.
先创建一个应用Test2,把Test1里面创建AIDL时生成的aidl文件夹直接copy到Test2里,然后Make Project.接着在Test2里bindService就可以了.
package com.t2mobile.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.t2mobile.test1.ITestaidl;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("com.t2m.testservice");
intent.setPackage("com.t2mobile.test1");
bindService(intent,conn,BIND_AUTO_CREATE);
Log.i("test00","===onCreate==");
}
private ServiceConnection conn = new ServiceConnection() {
private ITestaidl mService;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ITestaidl.Stub.asInterface(service);
Log.i("test00"," ========");
try {
Log.i("test00",mService.getAge() + " ");
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
unbindService(conn);
}
};
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}
先装服务端app Test1,然后装客户端app Test2,但是会出现的问题是总是拿不到Test1里提供的数据"666",也就是bindService不成功,因为没有在Test2的AndroidManifest.xml配置queries标签去声明Test2与其交互的包名,配置后就可以拿到服务端app Test1提供的数据"666"了.