android跨进程通信(IPC):使用AIDL

简介:

AIDL的作用

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

选择AIDL的使用场合

官方文档特别提醒我们何时使用AIDL是必要的:只有你允许客户端从不同的应用程序为了进程间的通信而去访问你的service,以及想在你的service处理多线程。如果不需要进行不同应用程序间的并发通信(IPC),you should create your interface by implementing a Binder;或者你想进行IPC,但不需要处理多线程的,则implement your interface using a Messenger。无论如何,在使用AIDL前,必须要理解如何绑定service——bindService。如何绑定服务,请参考我的另一篇文章:http://blog.csdn.net/singwhatiwanna/article/details/9058143。这里先假设你已经了解如何使用bindService。

如何使用AIDL

1.先建立一个android工程,用作服务端

创建一个android工程,用来充当跨进程通信的服务端。

2.创建一个包名用来存放aidl文件

创建一个包名用来存放aidl文件,比如com.ryg.sayhi.aidl,在里面新建IMyService.aidl文件,如果需要访问自定义对象,还需要建立对象的aidl文件,这里我们由于使用了自定义对象Student,所以,还需要创建Student.aidl和Student.java。注意,这三个文件,需要都放在com.ryg.sayhi.aidl包里。下面描述如何写这三个文件。

IMyService.aidl代码如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. import com.ryg.sayhi.aidl.Student;  
  4.   
  5. interface IMyService {  
  6.   
  7.     List<Student> getStudent();  
  8.     void addStudent(in Student student);  
  9. }  
说明:
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的实例,进而通过实例来调用其方法。

Student.aidl代码如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. parcelable Student;  
说明:这里parcelable是个类型,首字母是小写的,和Parcelable接口不是一个东西,要注意。

Student.java代码如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. import java.util.Locale;  
  4.   
  5. import android.os.Parcel;  
  6. import android.os.Parcelable;  
  7.   
  8. public final class Student implements Parcelable {  
  9.   
  10.     public static final int SEX_MALE = 1;  
  11.     public static final int SEX_FEMALE = 2;  
  12.   
  13.     public int sno;  
  14.     public String name;  
  15.     public int sex;  
  16.     public int age;  
  17.   
  18.     public Student() {  
  19.     }  
  20.   
  21.     public static final Parcelable.Creator<Student> CREATOR = new  
  22.             Parcelable.Creator<Student>() {  
  23.   
  24.                 public Student createFromParcel(Parcel in) {  
  25.                     return new Student(in);  
  26.                 }  
  27.   
  28.                 public Student[] newArray(int size) {  
  29.                     return new Student[size];  
  30.                 }  
  31.   
  32.             };  
  33.   
  34.     private Student(Parcel in) {  
  35.         readFromParcel(in);  
  36.     }  
  37.   
  38.     @Override  
  39.     public int describeContents() {  
  40.         return 0;  
  41.     }  
  42.   
  43.     @Override  
  44.     public void writeToParcel(Parcel dest, int flags) {  
  45.         dest.writeInt(sno);  
  46.         dest.writeString(name);  
  47.         dest.writeInt(sex);  
  48.         dest.writeInt(age);  
  49.     }  
  50.   
  51.     public void readFromParcel(Parcel in) {  
  52.         sno = in.readInt();  
  53.         name = in.readString();  
  54.         sex = in.readInt();  
  55.         age = in.readInt();  
  56.     }  
  57.       
  58.     @Override  
  59.     public String toString() {  
  60.         return String.format(Locale.ENGLISH, "Student[ %d, %s, %d, %d ]", sno, name, sex, age);  
  61.     }  
  62.   
  63. }  
说明:通过AIDL传输非基本类型的对象,被传输的对象需要序列化,序列化功能java有提供,但是android sdk提供了更轻量级更方便的方法,即实现Parcelable接口,关于android的序列化,我会在以后写文章介绍。这里只要简单理解一下就行,大意是要实现如下函数
readFromParcel : 从parcel中读取对象
writeToParcel :将对象写入parcel
describeContents:返回0即可
Parcelable.Creator<Student> CREATOR:这个照着上面的代码抄就可以
需要注意的是,readFromParcel和writeToParcel操作数据成员的顺序要一致

3.创建服务端service

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

问题:问题来了,有可能你的service只想让某个特定的apk使用,而不是所有apk都能使用,这个时候,你需要重写Stub中的onTransact方法,根据调用者的uid来获得其信息,然后做权限认证,如果返回true,则调用成功,否则调用会失败。对于其他apk,你只要在onTransact中返回false就可以让其无法调用IMyService中的方法,这样就可以解决这个问题了。

4. 在AndroidMenifest中声明service

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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>  

说明:上述的 <action android:name="com.ryg.sayhi.MyService" />是为了能让其他apk隐式bindService,通过隐式调用的方式来起activity或者service,需要把category设为default,这是因为,隐式调用的时候,intent中的category默认会被设置为default。

5. 新建一个工程,充当客户端

新建一个客户端工程,将服务端工程中的com.ryg.sayhi.aidl包整个拷贝到客户端工程的src下,这个时候,客户端com.ryg.sayhi.aidl包是和服务端工程完全一样的。如果客户端工程中不采用服务端的包名,客户端将无法正常工作,比如你把客户端中com.ryg.sayhi.aidl改一下名字,你运行程序的时候将会crash,也就是说,客户端存放aidl文件的包必须和服务端一样。客户端bindService的代码就比较简单了,如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.ryg.sayhi.aidl.IMyService;  
  2. import com.ryg.sayhi.aidl.Student;  
  3.   
  4. public class MainActivity extends Activity implements OnClickListener {  
  5.   
  6.     private static final String ACTION_BIND_SERVICE = "com.ryg.sayhi.MyService";  
  7.     private IMyService mIMyService;  
  8.   
  9.     private ServiceConnection mServiceConnection = new ServiceConnection()  
  10.     {  
  11.         @Override  
  12.         public void onServiceDisconnected(ComponentName name)  
  13.         {  
  14.             mIMyService = null;  
  15.         }  
  16.   
  17.         @Override  
  18.         public void onServiceConnected(ComponentName name, IBinder service)  
  19.         {  
  20.             //通过服务端onBind方法返回的binder对象得到IMyService的实例,得到实例就可以调用它的方法了  
  21.             mIMyService = IMyService.Stub.asInterface(service);  
  22.             try {  
  23.                 Student student = mIMyService.getStudent().get(0);  
  24.                 showDialog(student.toString());  
  25.             } catch (RemoteException e) {  
  26.                 e.printStackTrace();  
  27.             }  
  28.   
  29.         }  
  30.     };  
  31.   
  32.     @Override  
  33.     protected void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.activity_main);  
  36.         Button button1 = (Button) findViewById(R.id.button1);  
  37.         button1.setOnClickListener(new OnClickListener() {  
  38.   
  39.     @Override  
  40.     public void onClick(View view) {  
  41.         if (view.getId() == R.id.button1) {  
  42.             Intent intentService = new Intent(ACTION_BIND_SERVICE);  
  43.             intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  44.             MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);  
  45.         }  
  46.   
  47.     }  
  48.   
  49.     public void showDialog(String message)  
  50.     {  
  51.         new AlertDialog.Builder(MainActivity.this)  
  52.                 .setTitle("scott")  
  53.                 .setMessage(message)  
  54.                 .setPositiveButton("确定"null)  
  55.                 .show();  
  56.     }  
  57.       
  58.     @Override  
  59.     protected void onDestroy() {  
  60.         if (mIMyService != null) {  
  61.             unbindService(mServiceConnection);  
  62.         }  
  63.         super.onDestroy();  
  64.     }  
  65. }  

运行效果

可以看到,当点击按钮1的时候,客户端bindService到服务端apk,并且调用服务端的接口mIMyService.getStudent()来获取学生列表,并且把返回列表中第一个学生的信息显示出来,这就是整个ipc过程,需要注意的是:学生列表是另一个apk中的数据,通过aidl,我们才得到的。另外,如果你在onTransact中返回false,将会发现,获取的学生列表是空的,这意味着方法调用失败了,也就是实现了权限认证。
相关文章
|
4天前
|
Android开发
Android JNI与CAN通信遇到的问题总结
Android JNI与CAN通信遇到的问题总结
26 1
|
1月前
|
消息中间件 安全 Linux
线程同步与IPC:单进程多线程环境下的选择与权衡
线程同步与IPC:单进程多线程环境下的选择与权衡
58 0
|
1月前
|
消息中间件 Unix Linux
Linux进程间通信(IPC)介绍:详细解析IPC的执行流程、状态和通信机制
Linux进程间通信(IPC)介绍:详细解析IPC的执行流程、状态和通信机制
55 1
|
1月前
|
消息中间件 Linux API
C/C++ 进程间通信system V IPC对象超详细讲解(系统性学习day9)
C/C++ 进程间通信system V IPC对象超详细讲解(系统性学习day9)
|
24天前
|
安全 Linux API
Android进程与线程
Android进程与线程
18 0
|
1月前
|
消息中间件 存储 网络协议
Linux IPC 进程间通讯方式的深入对比与分析和权衡
Linux IPC 进程间通讯方式的深入对比与分析和权衡
69 0
|
1月前
|
消息中间件 Linux API
跨进程通信设计:Qt 进程间通讯类全面解析
跨进程通信设计:Qt 进程间通讯类全面解析
81 0
|
1月前
|
消息中间件 并行计算 网络协议
探秘高效Linux C/C++项目架构:让进程、线程和通信方式助力你的代码飞跃
探秘高效Linux C/C++项目架构:让进程、线程和通信方式助力你的代码飞跃
34 0
|
1月前
|
消息中间件 Linux
Linux进程间通信(IPC)教程 Linux共享内存介绍:介绍POSIX共享内存的基本概念、用途和编程实践
Linux进程间通信(IPC)教程 Linux共享内存介绍:介绍POSIX共享内存的基本概念、用途和编程实践
25 2
|
1月前
|
存储 Linux 程序员
Linux进程间通信(IPC)教程 Linux信号量:讲解POSIX信号量在Linux系统进程间通信中的编程实践
Linux进程间通信(IPC)教程 Linux信号量:讲解POSIX信号量在Linux系统进程间通信中的编程实践
21 1

相关实验场景

更多