Android进程间通信方式有4种:
Activity通过Intent与其他进程Activity通信(Component或隐式Intent)
利用BroadcastReceiver进行进程间通信
通过ContentProvider实现进程间通信
AIDL
前三种比较简单,这里不多做介绍,主要介绍一下AIDL的使用。
(1)服务端
创建一个AIDLFunctions.aidl文件(记住文件所在包路径,客户端的.aidl文件也用存在相同的包路径下),给该接口添加一个测试用的方法,我这里添加的是show()。
interface AIDLFunctions {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
void show();
}
Rebuild Project之后,会生成如下的java文件,之后我们便可以在代码中使用该接口了。
创建一个Service
public class AIDLService extends Service {
@Override
public void onCreate() {
super.onCreate();
System.out.println("##!##" + "service onCreate");
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("##!##" + Process.myPid() + "");
return mBinder;
}
private final AIDLFunctions.Stub mBinder = new AIDLFunctions.Stub() {
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) {
// Does nothing
}
@Override
public void show() throws RemoteException {
System.out.println("-----------有人调用show()-----------");
}
};
}
在ManiFest文件中注册Service并添加一个唯一的Action标识。
<service
android:name="com.example.draggridview.service.AIDLService">
<intent-filter>
<action android:name="com.example.draggridview.service.AIDLSERVICE"/>
</intent-filter>
</service>
(2)客户端
创建一个AIDLFunctions.aidl文件,加入和服务端.aidl文件相同的代码(和服务端的包路径要完全相同,可以直接从服务端拷贝过来)
Rebuild Project之后,会生成如下的java文件,之后我们便可以在代码中使用该接口了。
在初始化或是其他需要调用服务端服务的位置进行服务连接。
AIDLFunctions aidlFunctions;
ServiceConnection serviceConnection;
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("--------------------ServiceConnected----------------------");
aidlFunctions = AIDLFunctions.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("--------------------ServiceDisconnected----------------------");
}
};
//5.0之后必须显示调用Service,所以添加setPackage操作
Intent intent = new Intent();
intent.setAction("com.example.draggridview.service.AIDLSERVICE");
intent.setPackage("com.example.draggridview");
//注意,bindService是个异步的操作,一定要确保onServiceConnected回调成功,才说明服务绑定成功,然后服务才能生效
boolean bindServiceSuccess = bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
然后调用服务中的方法。
//bindService异步回调onServiceConnected成功后,调用show才好使,否则aidlFunctions为null,就会报错
try {
aidlFunctions.show();
} catch (RemoteException e) {
e.printStackTrace();
}
测试结果