AIDL的全称,Android Interface Definition Language。简单来说,AIDL的作用是让你可以在自己的APP里绑定一个其他APP的service。这样一个APP可以和另一个APP交互。
代码实现说明
两个应用之间通信。先创建两个工程。
首先第一个
工程名称OneProject,新建一个aidl文件。

内容如下
package com.example.myapplication;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
此方法可以忽略。这是说明aidl可传递的基本类型
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
//定义一个传递方法
String getName();
}
在项目中新建一个服务(service),注意,在onBind中返回一个自定义的Binder类,MyBinder继承IMyAidlInterface.Stub,然后重写里边的方法getName返回要传递的信息数据。
package com.example.myapplication.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import com.example.myapplication.IMyAidlInterface;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
class MyBinder extends IMyAidlInterface.Stub{
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public String getName() throws RemoteException {
return "test,数据传递显示";
}
}
}
修改AndroidManifest.xml,添加该service,并在intent-filter中添加action标签,客户端将通过该标签绑定该服务。

到这里第一个项目的准备工作完成。
接下来第二个项目
创建第二个工程TwoProject,将第一个项目中的整个aidl文件夹复制过来,要保证目录结构一致。确保所有使用的aidl文件都复制过来并且目录一致。简单说两个项目都用到的东西要各一份一模一样,如果要是自定义的类型,那就aidl文件以及自己实现的序列化类型。

接下来是MainActivity中的代码,绑定服务。
public class MainActivity extends AppCompatActivity {
private Button button;
private IMyAidlInterface iMyAidlInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.btn_tost);
Intent intent=new Intent();
intent.setAction("com.example.myapplication.service.MyService");
intent.setPackage("com.example.myapplication");
bindService(intent,conn,BIND_AUTO_CREATE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Log.i("deede",iMyAidlInterface.getName());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public ServiceConnection conn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMyAidlInterface=IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
Intent完成远程启动service,如果是Android版本高于5.0.选择隐式启动远程service、需要设置package,注意的是这个package是第一个项目的包名。
语法和Java语法的细微区别
1,不能用private,public,protect修饰方法
2,支持传递Java的基本数据类型,(byte、short、int、long、float、double、char、boolean),String,CharSequence,List(接受端必须是ArrayList),Map(接收端必须是HashMap),其他自定义的类型需要实现Parcelable序列化。
3,Aidl定义的接口和实现Parcelable序列化的类必须import,即使在相同的包结构下,其余的类型不需要import
4,对于基本数据类型,也不是String和CharSequence类型的,需要有方向指示,包括in(表示由客户端设置),out(表示由服务端设置),inout,(表示两者均可设置)
参考链接如下
https://blog.csdn.net/songkai0825/article/details/89345042
网友评论