aidl 传递对象

来源:互联网 发布:淘宝女鞋品牌大全 编辑:程序博客网 时间:2024/05/20 23:33
  1. 第一:实现Parcelable接口 
  2. 第二:定义一个Parcelable.Creator类型的CREATOR对象 
  3. 第三:要提供一个Booka.aidl文件,其中内容为parcelable Booka,定义了之后,在其他aidl文件中引用Booka时便不会提示出错了。 
  4. Booka.java
  5. public class Booka implements Parcelable {


    private String bookName;
    private int bookPrice;




    public String getBookName() {
    return bookName;
    }


    public void setBookName(String bookName) {
    this.bookName = bookName;
    }


    public int getBookPrice() {
    return bookPrice;
    }


    public void setBookPrice(int bookPrice) {
    this.bookPrice = bookPrice;
    }


    public int describeContents() {
    return 0;
    }


    public void writeToParcel(Parcel parcel, int flags) {
    parcel.writeString(bookName);
    parcel.writeInt(bookPrice);
    }


    public static final Parcelable.Creator<Booka> CREATOR = new Creator<Booka>() {
    public Booka createFromParcel(Parcel source) {
    Booka a=new Booka();
    a.setBookName(source.readString());
    a.setBookPrice(source.readInt());
    return a;
    }


    public Booka[] newArray(int size) {
    return new Booka[size];
    }
    };


    }
  6. import 导入相应的包;
  7. Booka.aidl     parcelable Booka;
  8. Ibooka
  9. interface Ibooka{
    Booka getBook();
    }
  10. 服务端代码
  11. public class RemoteService extends Service {


    private final static String TAG = "RemoteService";


    @Override
    public IBinder onBind(Intent intent) {
    Log.i(TAG, "执行了OnBind");
    return new MyBinder();
    }


    private class MyBinder extends aaaa.Stub {


    @Override
    public Booka getBook() throws RemoteException {
    Booka a = new Booka();
    a.setBookName("金瓶梅");
    a.setBookPrice(125);


    return a;
    }


    }
    }
  12. 客户端代码
  13. private class MyServiceConnection implements ServiceConnection {


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    // TODO Auto-generated method stub
    aaaa asInterface = aaaa.Stub.asInterface(service);
    if (asInterface == null) {
    return;
    }
    try {
  14.                                 //获取另一个程序的Booka对象
    Booka allInfo = asInterface.getBook();

  15. } catch (RemoteException e) {
    e.printStackTrace();
    }
    }


    @Override
    public void onServiceDisconnected(ComponentName name) {
    // TODO Auto-generated method stub


    }


    }


    MyServiceConnection connection = new MyServiceConnection();
  16. Intent intent = new Intent(“隐士意图的action”);
    bindService(intent, connection, Context.BIND_AUTO_CREATE);

原创粉丝点击