`
houchangxi
  • 浏览: 63292 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

android的aidl进程间通讯(一)

阅读更多



     一. 概述:
     跨进程通信(AIDL),主要实现进程(应用)间数据共享功能。
     二. 实现流程:
     1. 服务器端实现:
        (1)目录结构,如下图:

           

     (2)实现*.aidl文件:
      A. IAIDLService.aidl实现:


Java代码:

  1. import com.focus.aidl.Person;
  2. interface IAIDLService {
  3. String getName();
  4. Person getPerson();
  5. }
复制代码

      B. Person.aidl实现:

        parcelable Person;
        (3)进程间传递对象必需实现Parcelable或Serializable接口,下面是被传递的Person对象实现:

Java代码:

  1. package eoe.demo;

  2. import android.os.Parcel;
  3. import android.os.Parcelable;

  4. public class Person implements Parcelable {

  5. private String name;
  6. private int age;

  7. public Person() {
  8. }

  9. public Person(Parcel source) {
  10. name = source.readString();
  11. age = source.readInt();
  12. }

  13. public String getName() {
  14. return name;
  15. }

  16. public void setName(String name) {
  17. this.name = name;
  18. }

  19. public int getAge() {
  20. return age;
  21. }

  22. public void setAge(int age) {
  23. this.age = age;
  24. }

  25. public int describeContents() {
  26. return
  27. 0;
  28. }

  29. public void writeToParcel(Parcel dest, int flags) {
  30. dest.writeString(name);
  31. dest.writeInt(age);
  32. }

  33. public static final Parcelable.Creator<;Person> CREATOR = new Creator<;Person>() {
  34. public Person[] newArray(int size) {
  35. return
  36. new Person[size];
  37. }

  38. public Person createFromParcel(Parcel source) {
  39. return
  40. new Person(source);
  41. }
  42. };

  43. }
复制代码


      (4)实现IAIDLService.aidl文件中定义的接口,并定义Service,在Service被bind时返回此实现类:

Java代码:

  1. package eoe.demo;

  2. import com.focus.aidl.IAIDLService.Stub;
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.IBinder;
  6. import android.os.RemoteException;

  7. public class AIDLServiceImpl extends Service {

  8. @Override
  9. public IBinder onBind(Intent intent) {
  10. return mBinder;
  11. }

  12. /**
  13. * 在AIDL文件中定义的接口实现。
  14. */
  15. private IAIDLService.Stub mBinder = new Stub() {

  16. public String getName() throws RemoteException {
  17. return
  18. "mayingcai";
  19. }

  20. public Person getPerson() throws RemoteException {
  21. Person mPerson = new Person();

  22. mPerson.setName("mayingcai");
  23. mPerson.setAge(24);

  24. return mPerson;
  25. }

  26. };

  27. }
复制代码


(5)在AndroidManifest.xml文件中注册Service:

Java代码:

  1. <service android:name = ".AIDLServiceImpl" android:process = ":remote">

  2. <intent-filter>
  3. <action android:name = "com.focus.aidl.IAIDLService" />
  4. </intent-filter>

  5. </service>
复制代码
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics