前言
java
为使应用程序之间可以彼此通讯,Android提供了IPC (Inter Process Communication,进程间通讯)的一种独特实现: AIDL (Android Interface Definition Language, Android接口定义语言)。android
网上看了几篇关于AIDL的文章,写得都很不错,不过例子构造大多略微复杂: 创建两个Android项目,一个是client,一个是server(提供service)。app
这篇文章将经过一个项目来介绍AIDL用法,包含了service和client。可能简单了些,不太轻省许多。
ide
这篇博文包含如下三个部分:
工具
1、AIDL介绍测试
2、定义this
三、用例: HelloSumAIDLspa
3.一、建立工程线程
3.二、定义AIDL文件code
3.三、实现远程服务(Service)
3.四、“暴露”服务
3.五、相关代码
1、 AIDL介绍
在Android中,每一个应用(Application)执行在它本身的进程中,没法直接调用到其余应用的资源,这也符合“沙箱”的理念。所谓沙箱原理,通常来讲用在移动电话业务中,简单地说旨在部分地或所有地隔离应用程序。关于沙箱技术咱们这里就很少作介绍了,能够参看51CTO的这篇文章。
所以,在Android中,当一个应用被执行时,一些操做是被限制的,好比访问内存,访问传感器,等等。这样作能够最大化地保护系统,省得应用程序“随心所欲”。
那咱们有时须要在应用间交互,怎么办呢?因而,Android须要实现IPC协议。然而,这个协议仍是有点复杂,主要由于须要实现数据管理系统(在进程或线程间传递数据)。为了暂时减缓这个“会呼吸的痛”,Android为咱们实现了本身的IPC,也就是梁静茹,oh,sorry,是AIDL :]
2、 定义
AIDL是IPC的一个轻量级实现,用了对于Java开发者来讲很熟悉的语法。Android也提供了一个工具,能够自动建立Stub(类构架,类骨架)。当咱们须要在应用间通讯时,咱们须要按如下几步走:
1. 定义一个AIDL接口
2. 为远程服务(Service)实现对应Stub
3. 将服务“暴露”给客户程序使用
3、 用例: HelloSumAIDL
AIDL的语法很相似Java的接口(Interface),只须要定义方法的签名。
AIDL支持的数据类型与Java接口支持的数据类型有些不一样
1. 全部基础类型(int, char, 等)
2. String,List,Map,CharSequence等类
3. 其余AIDL接口类型
4. 全部Parcelable的类
为了更好地展现AIDL的用法,咱们来看一个很简单的例子: 两数相加。
3.1建立工程
事不宜迟,咱们就建立一个Android项目。如下是项目的基本信息(不必定要同样):
- 项目名称: HelloSumAIDL
- 目标平台: 4.3
- 包名: com.android.hellosumaidl
- Activity名称: HelloSumAidlActivity
3.2 建立工程
在com.android.hellosumaidl这个包中,新建一个普通文件(New->File),取名为 IAdditionService.aidl。在这个文件中输入如下代码:
package com.android.hellosumaidl; // Interface declaration interface IAdditionService { // You can pass the value of in, out or inout // The primitive types (int, boolean, etc) are only passed by in int add(in int value1, in int value2); }
一旦文件被保存,Android的AIDL工具会在gen/com/android/hellosumaidl这个文件夹里自动生成对应的IAdditionService.java这个文件。由于是自动生成的,因此无需改动。这个文件里就包含了Stub,咱们接下来要为咱们的远程服务实现这个Stub。
3.3 实现远程服务
首先咱们在com.android.hellosumaidl这个包中新建一个类,取名叫AdditionService.java。为了实现咱们的服务,咱们须要让这个类中的onBind方法返回一个IBinder类的对象。这个IBinder类的对象就表明了远程服务的实现。为了实现这个服务,咱们要用到自动生成的子类IAdditionService.Stub。在其中,咱们也必须实现咱们以前在AIDL文件中定义的add()函数。下面是咱们远程服务的代码:
package com.android.hellosumaidl; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; /* * This class exposes the service to client */ public class AdditionService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public IBinder onBind(Intent intent) { return new IAdditionService.Stub() { /* * Implement com.android.hellosumaidl.IAdditionService.add(int, int) */ @Override public int add(int value1, int value2) throws RemoteException { return value1 + value2; } }; } @Override public void onDestroy() { super.onDestroy(); } }
3.4 “暴露”服务
一旦实现了服务中的onBind方法,咱们就能够把客户程序(在这里是HelloSumAidlActivity.java)与服务链接起来了。为了创建这样的一个连接,咱们须要实现ServiceConnection类。咱们在HelloSumAidlActivity.java建立一个内部类AdditionServiceConnection,这个类继承ServiceConnection类,而且重写了它的两个方法:onServiceConnected和onServiceDisconnected。下面给出内部类的代码:
/* * This inner class is used to connect to the service */ class AdditionServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { service = IAdditionService.Stub.asInterface((IBinder)boundService); Toast.makeText(HelloSumAidlActivity.this, "Service connected", Toast.LENGTH_LONG).show(); } public void onServiceDisconnected(ComponentName name) { service = null; Toast.makeText(HelloSumAidlActivity.this, "Service disconnected", Toast.LENGTH_LONG).show(); } }
这个方法接收一个远程服务的实现做为参数。这个实现随后被转换(cast)为咱们本身的AIDL的实现。咱们使用 IAdditionService.Stub.asInterface((IBinder)boundService)。
3.5 相关代码
为了完成咱们的测试项目,咱们须要首先改写main.xml(主界面的格局文件)和string.xml (字符串定义文件):
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:textSize="22sp" /> <EditText android:id="@+id/value1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/hint1" > </EditText> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/plus" android:textSize="36sp" /> <EditText android:id="@+id/value2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/hint2" > </EditText> <Button android:id="@+id/buttonCalc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/equal" > </Button> <TextView android:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/result" android:textSize="36sp" /> </LinearLayout>
string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">HelloSumAIDL</string> <string name="hello">Hello Sum AIDL</string> <string name="result">Result</string> <string name="plus">+</string> <string name="equal">=</string> <string name="hint1">Value 1</string> <string name="hint2">Value 2</string> </resources>
最后,咱们的HelloSumAidlActivity.java以下:
package com.android.hellosumaidl; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; public class HelloSumAidlActivity extends Activity { IAdditionService service; AdditionServiceConnection connection; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initService(); Button buttonCalc = (Button)findViewById(R.id.buttonCalc); buttonCalc.setOnClickListener(new OnClickListener() { TextView result = (TextView)findViewById(R.id.result); EditText value1 = (EditText)findViewById(R.id.value1); EditText value2 = (EditText)findViewById(R.id.value2); @Override public void onClick(View v) { int v1, v2, res = -1; v1 = Integer.parseInt(value1.getText().toString()); v2 = Integer.parseInt(value2.getText().toString()); try { res = service.add(v1, v2); } catch (RemoteException e) { e.printStackTrace(); } result.setText(Integer.valueOf(res).toString()); } }); } @Override protected void onDestroy() { super.onDestroy(); releaseService(); } /* * This inner class is used to connect to the service */ class AdditionServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { service = IAdditionService.Stub.asInterface((IBinder)boundService); Toast.makeText(HelloSumAidlActivity.this, "Service connected", Toast.LENGTH_LONG).show(); } public void onServiceDisconnected(ComponentName name) { service = null; Toast.makeText(HelloSumAidlActivity.this, "Service disconnected", Toast.LENGTH_LONG).show(); } } /* * This function connects the Activity to the service */ private void initService() { connection = new AdditionServiceConnection(); Intent i = new Intent(); i.setClassName("com.android.hellosumaidl", com.android.hellosumaidl.AdditionService.class.getName()); boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE); } /* * This function disconnects the Activity from the service */ private void releaseService() { unbindService(connection); connection = null; } }
将此项目运行起来,获得的两个截图以下:
Fig 1 : 填写数字前
Fig 2 : 按下计算按钮后
后记
附上测试项目的Android代码包