[关闭]
@linux1s1s 2019-02-14T02:28:08.000000Z 字数 7394 阅读 2659

Android 进程间通信IPC_AIDL

AndroidProcess 2015-04


AIDL概念

AIDL (Android Interface Definition Language) 是一种IDL 语言,用于生成可以在Android设备上两个进程之间进行进程间通信(interprocess communication, IPC)的代码。如果在一个进程中(例如Activity)要调用另一个进程中(例如Service)对象的操作,就可以使用AIDL生成可序列化的参数。
AIDL IPC机制是面向接口的,像COM或Corba一样,但是更加轻量级。它是使用代理类在客户端和实现端传递数据。
上面概念性的东西比较浓重,简单的说就是通常两个App之间如何交互信息?这个就是IPC。

AIDL服务端App

新建 com.ryg.sayhi.aidl 包,然后在这个包下新建四个类
分别是:

Student.java

注意,必须实现Parcelable接口,这是android sdk提供的更轻量级更方便的方法。

  1. package com.ryg.sayhi.aidl;
  2. import java.util.Locale;
  3. import android.os.Parcel;
  4. import android.os.Parcelable;
  5. public final class Student implements Parcelable {
  6. public static final int SEX_MALE = 1;
  7. public static final int SEX_FEMALE = 2;
  8. public int sno;
  9. public String name;
  10. public int sex;
  11. public int age;
  12. public Student() {
  13. }
  14. public static final Parcelable.Creator<Student> CREATOR = new
  15. Parcelable.Creator<Student>() {
  16. public Student createFromParcel(Parcel in) {
  17. return new Student(in);
  18. }
  19. public Student[] newArray(int size) {
  20. return new Student[size];
  21. }
  22. };
  23. private Student(Parcel in) {
  24. readFromParcel(in);
  25. }
  26. @Override
  27. public int describeContents() {
  28. return 0;
  29. }
  30. @Override
  31. public void writeToParcel(Parcel dest, int flags) {
  32. dest.writeInt(sno);
  33. dest.writeString(name);
  34. dest.writeInt(sex);
  35. dest.writeInt(age);
  36. }
  37. public void readFromParcel(Parcel in) {
  38. sno = in.readInt();
  39. name = in.readString();
  40. sex = in.readInt();
  41. age = in.readInt();
  42. }
  43. @Override
  44. public String toString() {
  45. return String.format(Locale.ENGLISH, "Student[ %d, %s, %d, %d ]", sno, name, sex, age);
  46. }
  47. }

Student.aidl

  1. package com.ryg.sayhi.aidl;
  2. parcelable Student;

这里parcelable是个类型,首字母是小写的,和Parcelable接口不是一个东西,要注意。

IMyService.aidl

  1. package com.ryg.sayhi.aidl;
  2. import com.ryg.sayhi.aidl.Student;
  3. interface IMyService {
  4. List<Student> getStudent();
  5. void addStudent(in Student student);
  6. }

aidl中支持的参数类型为:基本类型(int,long,char,boolean等),String,CharSequence,List,Map,其他类型必须使用import导入,即使它们可能在同一个包里,比如上面的Student,尽管它和IMyService在同一个包中,但是还是需要显示的import进来。
另外,接口中的参数除了aidl支持的类型,其他类型必须标识其方向:到底是输入还是输出抑或两者兼之,用in,out或者inout来表示,上面的代码我们用in标记,因为它是输入型参数。
在gen下面可以看到,eclipse为我们自动生成了一个代理类
public static abstract class Stub extends android.os.Binder implements com.ryg.sayhi.aidl.IMyService
可见这个Stub类就是一个普通的Binder,只不过它实现了我们定义的aidl接口。它还有一个静态方法
public static com.ryg.sayhi.aidl.IMyService asInterface(android.os.IBinder obj)
这个方法很有用,通过它,我们就可以在客户端中得到IMyService的实例,进而通过实例来调用其方法。

Service

  1. public class MyService extends Service
  2. {
  3. private final static String TAG = "MyService";
  4. private static final String PACKAGE_SAYHI = "com.example.test";
  5. private NotificationManager mNotificationManager;
  6. private boolean mCanRun = true;
  7. private List<Student> mStudents = new ArrayList<Student>();
  8. //这里实现了aidl中的抽象函数
  9. private final IMyService.Stub mBinder = new IMyService.Stub() {
  10. @Override
  11. public List<Student> getStudent() throws RemoteException {
  12. synchronized (mStudents) {
  13. return mStudents;
  14. }
  15. }
  16. @Override
  17. public void addStudent(Student student) throws RemoteException {
  18. synchronized (mStudents) {
  19. if (!mStudents.contains(student)) {
  20. mStudents.add(student);
  21. }
  22. }
  23. }
  24. //在这里可以做权限认证,return false意味着客户端的调用就会失败,比如下面,只允许包名为com.example.test的客户端通过,
  25. //其他apk将无法完成调用过程
  26. public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
  27. throws RemoteException {
  28. String packageName = null;
  29. String[] packages = MyService.this.getPackageManager().
  30. getPackagesForUid(getCallingUid());
  31. if (packages != null && packages.length > 0) {
  32. packageName = packages[0];
  33. }
  34. Log.d(TAG, "onTransact: " + packageName);
  35. if (!PACKAGE_SAYHI.equals(packageName)) {
  36. return false;
  37. }
  38. return super.onTransact(code, data, reply, flags);
  39. }
  40. };
  41. @Override
  42. public void onCreate()
  43. {
  44. Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
  45. thr.start();
  46. synchronized (mStudents) {
  47. for (int i = 1; i < 6; i++) {
  48. Student student = new Student();
  49. student.name = "student#" + i;
  50. student.age = i * 5;
  51. mStudents.add(student);
  52. }
  53. }
  54. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  55. super.onCreate();
  56. }
  57. @Override
  58. public IBinder onBind(Intent intent)
  59. {
  60. Log.d(TAG, String.format("on bind,intent = %s", intent.toString()));
  61. displayNotificationMessage("服务已启动");
  62. return mBinder;
  63. }
  64. @Override
  65. public int onStartCommand(Intent intent, int flags, int startId)
  66. {
  67. return super.onStartCommand(intent, flags, startId);
  68. }
  69. @Override
  70. public void onDestroy()
  71. {
  72. mCanRun = false;
  73. super.onDestroy();
  74. }
  75. private void displayNotificationMessage(String message)
  76. {
  77. Notification notification = new Notification(R.drawable.icon, message,
  78. System.currentTimeMillis());
  79. notification.flags = Notification.FLAG_AUTO_CANCEL;
  80. notification.defaults |= Notification.DEFAULT_ALL;
  81. PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
  82. new Intent(this, MyActivity.class), 0);
  83. notification.setLatestEventInfo(this, "我的通知", message,
  84. contentIntent);
  85. mNotificationManager.notify(R.id.app_notification_id + 1, notification);
  86. }
  87. class ServiceWorker implements Runnable
  88. {
  89. long counter = 0;
  90. @Override
  91. public void run()
  92. {
  93. // do background processing here.....
  94. while (mCanRun)
  95. {
  96. Log.d("scott", "" + counter);
  97. counter++;
  98. try
  99. {
  100. Thread.sleep(2000);
  101. } catch (InterruptedException e)
  102. {
  103. e.printStackTrace();
  104. }
  105. }
  106. }
  107. }
  108. }

为了表示service的确在活着,我通过打log的方式,每2s打印一次计数。上述代码的关键在于onBind函数,当客户端bind上来的时候,将IMyService.Stub mBinder返回给客户端,这个mBinder是aidl的存根,其实现了之前定义的aidl接口中的抽象函数。

另外有个地方需要注意:有可能你的service只想让某个特定的apk使用,而不是所有apk都能使用,这个时候,你需要重写Stub中的onTransact方法,根据调用者的uid来获得其信息,然后做权限认证,如果返回true,则调用成功,否则调用会失败

AIDL客户端App

新建一个客户端工程,将服务端工程中的com.ryg.sayhi.aidl包整个拷贝到客户端工程的src下,这个时候,客户端com.ryg.sayhi.aidl包是和服务端工程完全一样的。如果客户端工程中不采用服务端的包名,客户端将无法正常工作,比如你把客户端中com.ryg.sayhi.aidl改一下名字,你运行程序的时候将会crash,也就是说,客户端存放aidl文件的包必须和服务端一样。客户端bindService的代码就比较简单了,如下:

MainActivity

  1. import com.ryg.sayhi.aidl.IMyService;
  2. import com.ryg.sayhi.aidl.Student;
  3. public class MainActivity extends Activity implements OnClickListener {
  4. private static final String ACTION_BIND_SERVICE = "com.ryg.sayhi.MyService";
  5. private IMyService mIMyService;
  6. private ServiceConnection mServiceConnection = new ServiceConnection()
  7. {
  8. @Override
  9. public void onServiceDisconnected(ComponentName name)
  10. {
  11. mIMyService = null;
  12. }
  13. @Override
  14. public void onServiceConnected(ComponentName name, IBinder service)
  15. {
  16. //通过服务端onBind方法返回的binder对象得到IMyService的实例,得到实例就可以调用它的方法了
  17. mIMyService = IMyService.Stub.asInterface(service);
  18. try {
  19. Student student = mIMyService.getStudent().get(0);
  20. showDialog(student.toString());
  21. } catch (RemoteException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. };
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. Button button1 = (Button) findViewById(R.id.button1);
  31. button1.setOnClickListener(new OnClickListener() {
  32. @Override
  33. public void onClick(View view) {
  34. if (view.getId() == R.id.button1) {
  35. Intent intentService = new Intent(ACTION_BIND_SERVICE);
  36. intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  37. MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);
  38. }
  39. }
  40. public void showDialog(String message)
  41. {
  42. new AlertDialog.Builder(MainActivity.this)
  43. .setTitle("scott")
  44. .setMessage(message)
  45. .setPositiveButton("确定", null)
  46. .show();
  47. }
  48. @Override
  49. protected void onDestroy() {
  50. if (mIMyService != null) {
  51. unbindService(mServiceConnection);
  52. }
  53. super.onDestroy();
  54. }
  55. }

AndroidMenifest

  1. <service
  2. android:name="com.ryg.sayhi.MyService"
  3. android:process=":remote"
  4. android:exported="true" >
  5. <intent-filter>
  6. <category android:name="android.intent.category.DEFAULT" />
  7. <action android:name="com.ryg.sayhi.MyService" />
  8. </intent-filter>
  9. </service>

上述的 是为了能让其他apk隐式bindService,通过隐式调用的方式来起activity或者service,需要把category设为default,这是因为,隐式调用的时候,intent中的category默认会被设置为default。

运行结果

此处输入图片的描述

可以看到,当点击按钮1的时候,客户端bindService到服务端apk,并且调用服务端的接口mIMyService.getStudent()来获取学生列表,并且把返回列表中第一个学生的信息显示出来,这就是整个ipc过程,需要注意的是:学生列表是另一个apk中的数据,通过aidl,我们才得到的。另外,如果你在onTransact中返回false,将会发现,获取的学生列表是空的,这意味着方法调用失败了,也就是实现了权限认证。

本文转载和修改与博客:http://blog.csdn.net/singwhatiwanna/article/details/17041691

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注