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实现类及其包拷贝过来


更多相关文章

  1. Android一次刷机
  2. Android访问中央气象台的天气预报API得到天气数据
  3. Android(安卓)数据存储之SQLite数据库
  4. Android自带的TabLayout实现滑动翻页效果(实例)
  5. 04.Android的数据存储操作
  6. android 实现屏幕截图
  7. 浅谈Java中Collections.sort对List排序的两种方法
  8. mybatisplus的坑 insert标签insert into select无参数问题的解决
  9. python起点网月票榜字体反爬案例

随机推荐

  1. android中Http类的封装
  2. Android(安卓)Paint之shader(图像渲染)
  3. Android(安卓)退出程序的若干方法总结
  4. Android开源项目分类汇总(七)优秀项目
  5. Android在代码中设置控件的drawableLeft
  6. flutter methodchannel调用原生方法,实现
  7. Android控件之ScrollView(scrollbarStyle
  8. Android实战技巧之十二:Android(安卓)Stud
  9. ARCore1.2使用入门(一) ------ 将ARCore案
  10. Android(安卓)横竖屏切换设置的 configCh