1.创建android工程
2.创建aidl文件(不需要public类似的修饰)例如 IBankAccountService.aidl
interface IBankAccountService {
double calMondy(double sum);
}
3.自定义类继承Service并实现 onBind方法,在自定义类中可以设置多个变量实现多个aidl文件,根据onBind的Intent的action返回不同的IBinder对象
如:
public class CustomService extends Service {
//操作 可以有多个类似这样的变量,多个aidl
private IBankAccountService.Stub ibanAccountService=new IBankAccountService.Stub() {
@Override
public double calMondy(double sum) throws RemoteException {
return sum*10;
}
};
@Override
public IBinder onBind(Intent intent) {
return ibanAccountService;
}
}
4.进程间数据传递
/**
通过Android.os提供的Parcelable类型来传递数据,通常我们使用Eclipse+ADT插件来完成,在Eclipse中在Package Explorer view视图上单击鼠标右键,选择Create Aidl preprocess file for Parcelable classes(创建aidl预编译文件),最终我们创建一个名为android123.aidl文件
*/
import android.os.Parcel;
import android.os.Parcelable;
public final class Rect implements Parcelable {
public int left;
public int top;
public int right;
public int bottom;
public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
public Rect createFromParcel(Parcel in) {
return new Rect(in);
}
public Rect[] newArray(int size) {
return new Rect[size];
}
};
public Rect() {
}
private Rect(Parcel in) {
readFromParcel(in);
}
public void writeToParcel(Parcel out) { //当前数据写入到Parcel中
out.writeInt(left);
out.writeInt(top);
out.writeInt(right);
out.writeInt(bottom);
}
public void readFromParcel(Parcel in) { //从Parcel中读取数据
left = in.readInt();
top = in.readInt();
right = in.readInt();
bottom = in.readInt();
}
}
5.进程内使用(以下方式启动service)
IBankAccountService mService=null;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
mService = IBankAccountService.Stub.asInterface(service);
try {
System.out.println( mService.calMondy(20));
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
// 启动服务
Intent intent=new Intent();
intent.setClass(this, CustomService.class);
bindService(intent,
mConnection, Context.BIND_AUTO_CREATE);
当mService不等于null时就可以使用了
6.进程外使用(跨进程,注意:***保证拥有CustomService的项目已经装在手机里)
1.把IBankAccountService.aidl及其包拷入到目标工程(工程内此文件路径完全一致)
2.类似前面第5步一样启动服务,服务直接设置action的名字
3.如果需传递数据需要使用前面定义的Parcelable实现类传递,当然需要把前面定义的Parcelable实现类及其包拷贝过来
转载于:https://my.oschina.net/lgllfx/blog/625985