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 数据存储之SQLite数据库
  2. 04.Android的数据存储操作
  3. Android-缓存数据保存-通用方法
  4. 在Android中通过Java修改文件权限
  5. Android获取前台进程包名
  6. Android开发便签9:在android资源文件中定义字符串数组
  7. java/android 统计文件夹大小及删除文件夹下所有文件和路径

随机推荐

  1. ListView之setEmptyView的问题
  2. android中的VersionCode和VersionName到
  3. TextView和EidtText使用技巧
  4. android Handler 介绍
  5. 吹雪花demo,学习android传感器《IT蓝豹》
  6. 创建android文件系统(Root file system)
  7. 【Android(安卓)应用开发】 Android(安卓
  8. Android(安卓)安装卸载程序
  9. Android(安卓)splitActionBarWhenNarrow
  10. Android(安卓)自定义View及其在布局文件