一、定义

AIDL是用来解决进程间通信的(一般有四种方式:Activity、Service、ContentProvider、Broadcast Receiver),两个进程间无法直接通信,所以要用AIDL(属于前面提到的Service)来借助操作系统底层来间接进行通信,示意图如下:

AIDL全称为 Android Interface Definition Language,即Android接口定义语言。

二、AIDL开发(操作)流程

开发流程一般为:

1、定义AIDL文件(先在服务端定义,客户端也要定义,内容路服务端一样)

2、服务端实现接口

3、客户端调用接口

三、AIDL语法规则

语法规则如下:

1、语法跟Java的接口很相似

2、AIDL只支持方法,不能定义静态成员

3、AIDL运行方法有任何类型的参数(除short外)和返回值

4、除默认类型,均需要导包

四、AIDL支持的数据类型

1、除short外的基本数据类型

2、String, CharSequence

3、List(作为参数时,要指明是输入in 还是输出out), Map

4、Parcelable (自定义类型要实现 Parcelable 接口)

五、AIDL服务端与客户端之间的关系

六、AIDL适用场景

使用了IPC通信,多个客户端,多线程,否则可使用Binder或Messager

七、示例

1、在服务端定义自定义类型Person,实现 Parcelable 接口:

package com.atwal.aidl;

import android.os.Parcel;
import android.os.Parcelable; /**
* Created by Du on 2016/2/25.
*/
public class Person implements Parcelable {
private String name;
private int age; public Person(String name, int age) {
this.name = name;
this.age = age;
} public Person(Parcel source) {
this.name = source.readString();
this.age = source.readInt();
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public int describeContents() {
return 0;
} @Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.age);
} public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
} @Override
public Person[] newArray(int size) {
return new Person[0];
}
}; @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

2、在服务端定义 Person.aidl :

// IImoocAidl.aidl
package com.atwal.aidl; parcelable Person;

3、在服务端定义 IImoocAidl.aidl :

// IImoocAidl.aidl
package com.atwal.aidl; import com.atwal.aidl.Person; interface IImoocAidl { //计算两个数的和
int add(int num1, int num2); List<String> basicTypes(
byte aByte,
int aInt,
long aLong,
boolean aBoolean,
float aFloat,
double aDouble,
char aChar,
String aString,
in List<String> list); List<Person> addPerson(in Person person);
}

4、在服务端定义Service(注意要在AndroidManifest.xml中定义):

package com.atwal.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log; import java.util.ArrayList;
import java.util.List; /**
* Created by Du on 2016/2/25.
*/
public class IRemoteService extends Service { private ArrayList<Person> persons; /**
* 当客户端绑定到该服务的时候,会执行
*
* @param intent
* @return
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
persons = new ArrayList<>();
return iBinder;
} private IBinder iBinder = new IImoocAidl.Stub() { @Override
public int add(int num1, int num2) throws RemoteException {
Log.d("TAG", "收到了远程的请求,输入的参数是 " + num1 + " 和 " + num2);
return num1 + num2;
} @Override
public List<String> basicTypes(byte aByte, int aInt, long aLong, boolean aBoolean, float aFloat, double aDouble, char aChar, String aString, List<String> list) throws RemoteException {
return null;
} @Override
public List<Person> addPerson(Person person) throws RemoteException {
persons.add(person);
return persons;
}
};
}

5、在客户端添加Person类,内容和包名都跟服务端一样

6、在客户端添加Person.aidl文件,内容和包名都跟服务端一样

7、在客户端添加IImoocAidl.aidl文件,内客和包名都跟服务端一样

8、客户端调用

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.atwal.aidlclient.MainActivity"> <EditText
android:id="@+id/et_num1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="num1"
android:textSize="20sp" /> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="+"
android:textSize="20sp" /> <EditText
android:id="@+id/et_num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="num2"
android:textSize="20sp" /> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="="
android:textSize="20sp" /> <TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:id="@+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="AIDL远程计算" />
</LinearLayout>

代码:

package com.atwal.aidlclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView; import com.atwal.aidl.IImoocAidl;
import com.atwal.aidl.Person; import java.util.ArrayList;
import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText mEtNum1, mEtNum2;
private TextView mTvResult;
private Button mBtnAdd; private IImoocAidl iImoocAidl; private ServiceConnection conn = new ServiceConnection() { //绑定上服务的时候
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//拿到了远程的服务代理
iImoocAidl = IImoocAidl.Stub.asInterface(service);
} //断开服务的时候
@Override
public void onServiceDisconnected(ComponentName name) {
//回收资源
iImoocAidl = null;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); initView(); //应用一启动就绑定服务
bindSersvice();
} private void initView() {
mEtNum1 = (EditText) findViewById(R.id.et_num1);
mEtNum2 = (EditText) findViewById(R.id.et_num2);
mTvResult = (TextView) findViewById(R.id.tv_result);
mBtnAdd = (Button) findViewById(R.id.btn_add); mBtnAdd.setOnClickListener(this);
} @Override
public void onClick(View v) {
int num1 = Integer.parseInt(mEtNum1.getText().toString());
int num2 = Integer.parseInt(mEtNum2.getText().toString());
try {
//调用远程的服务
int res = iImoocAidl.add(num1, num2);
mTvResult.setText(String.valueOf(res));
} catch (RemoteException e) {
e.printStackTrace();
mTvResult.setText("错误了");
} try {
List<Person> persons = iImoocAidl.addPerson(new Person("atwal", 21));
Log.d("TAG", persons.toString());
} catch (RemoteException e) {
e.printStackTrace();
}
} private void bindSersvice() {
//获取到服务端
Intent intent = new Intent();
//新版本(5.0以上)必须显示Intent启动绑定服务
intent.setComponent(new ComponentName("com.atwal.aidl", "com.atwal.aidl.IRemoteService"));
bindService(intent, conn, Context.BIND_AUTO_CREATE);
} @Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn);
}
}

整个项目目录结构如下:

android中的AIDL学习笔记的更多相关文章

  1. 我的Android进阶之旅------>Android中编解码学习笔记

    编解码学习笔记(一):基本概念 媒体业务是网络的主要业务之间.尤其移动互联网业务的兴起,在运营商和应用开发商中,媒体业务份量极重,其中媒体的编解码服务涉及需求分析.应用开发.释放license收费等等 ...

  2. Android中的Telephony学习笔记(2)

    上一篇文章中学习了android.provider中Telephony类. 这一篇文章学习android.telephony包中的类,这些类是android提供给上层调用的API. 为监測基本电话信息 ...

  3. android中读取通讯录学习笔记

    1.读取通讯录时一次读取时,尽量少读取全部属性.特别是列表展示的时候.会让你的列表载入速度变得难以忍受,建议先载入少量属性.然后在详情的时候载入全部属性. 2.在读取一类属性的时候,建议用一个游标,且 ...

  4. Android(java)学习笔记167:Java中操作文件的类介绍(File + IO流)

    1.File类:对硬盘上的文件和目录进行操作的类.    File类是文件和目录路径名抽象表现形式  构造函数:        1) File(String pathname)       Creat ...

  5. Android(java)学习笔记110:Java中操作文件的类介绍(File + IO流)

    1.File类:对硬盘上的文件和目录进行操作的类.    File类是文件和目录路径名抽象表现形式  构造函数:        1) File(String pathname)       Creat ...

  6. Android(java)学习笔记233: 远程服务的应用场景(移动支付案例)

    一. 移动支付:       用户需要在移动终端提交账号.密码以及金额等数据 到 远端服务器.然后远端服务器匹配这些信息,进行逻辑判断,进而完成交易,返回交易成功或失败的信息给移动终端.用户提交账号. ...

  7. Android(java)学习笔记176: 远程服务的应用场景(移动支付案例)

    一. 移动支付:       用户需要在移动终端提交账号.密码以及金额等数据 到 远端服务器.然后远端服务器匹配这些信息,进行逻辑判断,进而完成交易,返回交易成功或失败的信息给移动终端.用户提交账号. ...

  8. Android自动化测试之Monkeyrunner学习笔记(一)

    Android自动化测试之Monkeyrunner学习笔记(一) 因项目需要,开始研究Android自动化测试方法,对其中的一些工具.方法和框架做了一些简单的整理,其中包括Monkey.Monkeyr ...

  9. Android 中的AIDL,Parcelable和远程服务

    Android 中的AIDL,Parcelable和远程服务      早期在学习期间便接触到AIDL,当时对此的运用也是一撇而过.只到近日在项目中接触到AIDL,才开始仔细深入.AIDL的作用    ...

随机推荐

  1. 初学Pollard Rho算法

    前言 \(Pollard\ Rho\)是一个著名的大数质因数分解算法,它的实现基于一个神奇的算法:\(MillerRabin\)素数测试(关于\(MillerRabin\),可以参考这篇博客:初学Mi ...

  2. Netbackup用于技术支持的问题报告(报障模版)

    在与支持部门联系以报告问题之前,请填写以下信息. 日期: _________________________记录以下产品.平台和设备信息:■ 产品及其版本级别.■ 服务器硬件类型和操作系统级别.■ 客 ...

  3. POJ 3565 Ants 【最小权值匹配应用】

    传送门:http://poj.org/problem?id=3565 Ants Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: ...

  4. Ubuntu连接上海大学校园网(ShuWlan-1x & Shu(For All))

    1.连接Shu(For All):直接连接,打开网页后可能会自动弹出登录页面,也可能需要点击浏览器菜单栏下方的跳转按钮. 2.连接ShuWlan-1x配置注意点: 认证方式:Protected EAP ...

  5. MVC学习四:Razor视图语法

    @{ Layout = null; } <hr /> <!DOCTYPE html> @this.GetType().Assembly.Location.ToString() ...

  6. P2939 改造路

    P2939 [USACO09FEB]改造路Revamping Trails 裸地分层图最短路 培训的时候考到过 但是-- 我考试的时候写了个基本没有的树状数组优化.然后顺利的被卡到了70分(裸的spf ...

  7. Android学习笔记_4_单元测试

    在实际开发中,开发android软件的过程需要不断地进行测试.而使用Junit测试框架,侧是正规Android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性. 1. ...

  8. Angularjs基础(七)

    AngularJS表单 AngularJS表单时输入控件的集合HTML控件 一下HTML input 元素被称为HTML 控件: input 元素 select元素 button元素 textarea ...

  9. ABAP术语-HTML

    HTML 原文:http://www.cnblogs.com/qiangsheng/archive/2008/02/19/1073298.html Hypertext Markup Language( ...

  10. Mybatis中多个参数的问题&&动态SQL&&查询结果与类的对应

    ### 1. 抽象方法中多个参数的问题 在使用MyBatis时,接口中的抽象方法只允许有1个参数,如果有多个参数,例如: Integer updatePassword( Integer id, Str ...