AIDL介绍和实例讲解
前言
为使应用程序之间能够彼此通信,Android提供了IPC (Inter Process Communication,进程间通信)的一种独特实现: AIDL (Android Interface Definition Language, Android接口定义语言)。
网上看了几篇关于AIDL的文章,写得都很不错,不过例子构造大多略微复杂: 建立两个Android项目,一个是client,一个是server(提供service)。
这篇文章将通过一个项目来介绍AIDL用法,包含了service和client。可能简单了些,不过轻省许多。
这篇博文包含以下两个部分:
1、AIDL介绍
2、定义
3、用例: HelloSumAIDL
3.1、创建工程
3.2、定义AIDL文件
3.3、实现远程服务(Service)
3.4、“暴露”服务
3.5、相关代码
一、 AIDL介绍
在Android中,每个应用(Application)执行在它自己的进程中,无法直接调用到其他应用的资源,这也符合“沙箱”的理念。所谓沙箱原理,一般来说用在移动电话业务中,简单地说旨在部分地或全部地隔离应用程序。关于沙箱技术我们这里就不多做介绍了,可以参看这篇文章。
因此,在Android中,当一个应用被执行时,一些操作是被限制的,比如访问内存,访问传感器,等等。这样做可以最大化地保护系统,免得应用程序“为所欲为”。
那我们有时需要在应用间交互,怎么办呢?于是,Android需要实现IPC协议。然而,这个协议还是有点复杂,主要因为需要实现数据管理系统(在进程或线程间传递数据)。为了暂时减缓这个“会呼吸的痛”,Android为我们实现了自己的IPC,也就是梁静茹,oh,sorry,是AIDL :]
二、 定义
AIDL是IPC的一个轻量级实现,用了对于Java开发者来说很熟悉的语法。Android也提供了一个工具,可以自动创建Stub(类构架,类骨架)。当我们需要在应用间通信时,我们需要按以下几步走:
1. 定义一个AIDL接口
2. 为远程服务(Service)实现对应Stub
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代码
百度云盘下载链接:http://pan.baidu.com/s/1gdeiK4F
AIDL介绍和实例讲解的更多相关文章
- Android开发之IPC进程间通信-AIDL介绍及实例解析
一.IPC进程间通信 IPC是进程间通信方法的统称,Linux IPC包括以下方法,Android的进程间通信主要采用是哪些方法呢? 1. 管道(Pipe)及有名管道(named pipe):管道可用 ...
- Android探索之旅 | AIDL原理和实例讲解
轉載自http://www.jianshu.com/p/ef86f682a8f9 -- 作者 谢恩铭 转载请注明出处 前言 为使应用程序之间能够彼此通信,Android提供了IPC (Inter Pr ...
- 多线程(五) Fork/Join框架介绍及实例讲解
什么是Fork/Join框架 Fork/Join框架是Java7提供了的一个用于并行执行任务的框架, 是一个把大任务分割成若干个小任务,最终汇总每个小任务结果后得到大任务结果的框架. 我们再通过For ...
- Express入门介绍vs实例讲解
下午在团队内部分享了express相关介绍,以及基于express的实例.内容提纲如下. 什么是Express 为什么要用Express 路由规则 一切皆中间件 实例:Combo Applicatio ...
- 4、qq物联SDK介绍及实例讲解
1.到QQ物联官网http://iot.open.qq.com中下载软件SDK S3C2440_20161122_1.6.205_r4288.tar.gz注意:在后续大家实际开发过程中,可能你会下载到 ...
- 实例讲解JQuery中this和$(this)区别
这篇文章主要介绍了实例讲解JQuery中this和$(this)的区别,this表示当前的上下文对象是一个html对象,可以调用html对象所拥有的属性和方法,$(this),代表的上下文对象是一个j ...
- S3C2440上RTC时钟驱动开发实例讲解(转载)
嵌入式Linux之我行,主要讲述和总结了本人在学习嵌入式linux中的每个步骤.一为总结经验,二希望能给想入门嵌入式Linux的朋友提供方便.如有错误之处,谢请指正. 共享资源,欢迎转载:http:/ ...
- 基于tcpdump实例讲解TCP/IP协议
前言 虽然网络编程的socket大家很多都会操作,但是很多还是不熟悉socket编程中,底层TCP/IP协议的交互过程,本文会一个简单的客户端程序和服务端程序的交互过程,使用tcpdump抓包,实例讲 ...
- 实例讲解基于 React+Redux 的前端开发流程
原文地址:https://segmentfault.com/a/1190000005356568 前言:在当下的前端界,react 和 redux 发展得如火如荼,react 在 github 的 s ...
随机推荐
- [android]APP启动界面——SplashActivity
概念 当前应用程序在启动的时候都会有一个展示自己公司LOGO和APP名字的界面.这个界面成为SplashActivity. 布局 <? xml version="1.0" e ...
- OC-Protocol实现业务代理
创建一个Protocol,相当于java的接口,但,有些方法不必实现,例如以下 #import <Foundation/Foundation.h> @protocol MyProtocol ...
- 智能生活 “视”不可挡——首届TCL杯HTML5智能电视开发大赛等你来挑战
http://www.csdn.net/article/2014-06-04/2820063-TCL-Smart-TV-Innovation-Competation
- 项目实践中--Git服务器的搭建与使用指南(转)
一.前言 Git是一款免费.开源的分布式版本控制系统,用以有效.高速的处理从很小到非常大的项目版本管理.在平时的项目开发中,我们会使用到Git来进行版本控制. Git的功能特性: 从一般开发者的角度来 ...
- hdu2639(背包求第k优解)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2639 题意:给出一行价值,一行体积,让你在v体积的范围内找出第k大的值 分析:dp[i][j][k]表 ...
- hdu3555(数位dp)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3555 题意:求区间[a,b]内包含有'49'的数的总个数. 分析:dp[pos][0]表示到第pos位 ...
- Android Studio使用心得 - 简单介绍与环境配置
FBI Warning:欢迎转载,但请标明出处:http://blog.csdn.net/codezjx/article/details/38544823,未经本人允许请勿用于商业用途.感谢支持! 关 ...
- 【转向Javascript系列】从setTimeout说事件循环模型
本文首发在alloyteam团队博客,链接地址http://www.alloyteam.com/2015/10/turning-to-javascript-series-from-settimeout ...
- 解压system.img
解压: All-Series:~$ simg2img system.img system.img.ext4 All-Series:~$ mkdir tmp All-Series:~$ mount -t ...
- 在Xshell中上传下载文件到本地(linux中从多次ssh登录的dbserver里面的文件夹)
在Xshell中上传下载文件到本地(linux中从多次ssh登录的dbserver里面的文件夹) 1 列出所有需要copy的sh文件 -bash-4.1$ ll /mysqllog/osw/*.sh ...