Android Service总结06 之AIDL
Android Service总结06 之AIDL
|
版本 |
版本说明 |
发布时间 |
发布人 |
|
V1.0 |
初始版本 |
2013-04-03 |
Skywang |
1 AIDL介绍
AIDL,即Android InterfaceDefinition Language。
Android使用AIDL来完成进程间通信(IPC),并且一般在服务需要接受不同应用多线程的请求时才需要使用AIDL;如果是同一个应用内的请求使用Binder实现即可;如果只是应用间通信而不是多线程处理的话使用Messenger,当然这两种情况也可以使用AIDL。本地进程和远程进程使用AIDL有所不同,本地进程内调用时会都在调用的线程内执行,远程进程使用是通过Service进程内一个由系统维护的线程池发出调用,所以可能是未知线程同时调用,需要注意线程安全问题。
2 AIDL示例
创建AIDL服务的步骤:
(01)创建.aidl文件。 .aidl是接口文件,它定义了服务所能提供的功能。
(02)实现.aidl所定义的接口。
(03)将接口开放给其它应用程序。
2.1 创建.aidl文件
(01)打开eclipse,新建工程”AIDLServiceImpl”,然后在工程的“com.text”包下创建“MyAIDLInterface.aidl”文件。
如下图:
(02)编辑“MyAIDLInterface.aidl”,提供doubleValue(int val)和halfValue(int value)服务。
“MyAIDLInterface.aidl”代码如下:
package com.test;
interface MyAIDLInterface {
void doubleValue(int val);
void halfValue(int val);
}
(03)编译工程,在“gen”目录下会自动生成与“MyAIDLInterface.aidl”对应的“MyAIDLInterface.java”文件。
如下图:
“MyAIDLInterface.java”代码如下:
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: F:\\workout\\android\\AIDLServiceImpl\\src\\com\\test\\MyAIDLInterface.aidl
*/
package com.test;
public interface MyAIDLInterface extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.test.MyAIDLInterface
{
private static final java.lang.String DESCRIPTOR = "com.test.MyAIDLInterface";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.test.MyAIDLInterface interface,
* generating a proxy if needed.
*/
public static com.test.MyAIDLInterface asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.test.MyAIDLInterface))) {
return ((com.test.MyAIDLInterface)iin);
}
return new com.test.MyAIDLInterface.Stub.Proxy(obj);
}
public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_doubleValue:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
this.doubleValue(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_halfValue:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
this.halfValue(_arg0);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.test.MyAIDLInterface
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
public void doubleValue(int val) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(val);
mRemote.transact(Stub.TRANSACTION_doubleValue, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
public void halfValue(int val) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(val);
mRemote.transact(Stub.TRANSACTION_halfValue, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_doubleValue = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_halfValue = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public void doubleValue(int val) throws android.os.RemoteException;
public void halfValue(int val) throws android.os.RemoteException;
}
2.2 实现.aidl所定义的接口
(04)在“com.test”包下新建文件MyAIDLService.java,并实现doubleValue(int val)和halfValue(int value)接口。
如下图:
MyAIDLService.java的代码如下:
package com.test; import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log; public class MyAIDLService extends Service{
private static final String TAG = "skywang-->MyAIDLService"; private MyAIDLInterface.Stub myBinder =
new MyAIDLInterface.Stub() { @Override
public void halfValue(int val) throws RemoteException {
Log.d(TAG, "halfValue val="+val/2); } @Override
public void doubleValue(int val) throws RemoteException {
Log.d(TAG, "doubleValue val="+val*2);
}
};
@Override
public void onCreate() {
super.onCreate();
} @Override
public void onDestroy(){
super.onDestroy();
} @Override
public IBinder onBind(Intent intent) {
return myBinder;
}
}
(05) 定义aidl对应的manifest
manifest内容如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" > <service android:name=".MyAIDLService" android:process=":remote">
<intent-filter>
<action android:name="com.test.MY_AIDL_SERVICE" />
</intent-filter>
</service> </application> </manifest>
至此,我们已经完成了.aidl服务的定义和实现。
2.3 将接口开放给其它应用程序
(06)新建一个工程“AIDLServiceTest”,然后在工程的“com.skywang”包下创建AIDLServiceTest.java;
(07)然后,将MyAIDLInterface.aidl文件拷贝到AIDLServiceTest工程的“com.test”包下。
如下图:

注意:.aidl所在的包名,必须和定义它的包名一样!(即MyAIDLInterface.aidl所在的定义它的工程的包为com.test;那么,调用MyAIDLInterface.aidl的程序,也必须把MyAIDLInterface.aidl放在com.test包下面)
(08)AIDLServiceTest.java首先必须实现ServiceConnection接口。
实现ServiceConnection接口的原因是:我们在后面调用.aidl服务的时候,必须通过bindService()去绑定服务;而bindService()需要用到ServiceConnection对象。
实现ServiceConnection很简单,只需要实现两个接口:
onServiceConnected —— 连上服务的回调函数。一般在此函数中,获取服务对象。
onServiceDisconnected —— 断开服务的回调函数。可以直接返回null。
ServiceConnection的实现代码如下:
private MyAIDLInterface mBinder = null;
private ServiceConnection mConnection = new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) {
mBinder = null;
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "Service connected!");
mBinder = MyAIDLInterface.Stub.asInterface(service);
}
};
(09)开始访问服务之前,我们要先通过bindService()绑定服务;使用完毕之后,通过unbindService()断开服务。
AIDLServiceTest.java代码如下:
package com.skywang; import android.app.Activity;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.ComponentName;
import android.content.Intent;
import android.content.Context;
import android.content.ServiceConnection;
import com.test.MyAIDLInterface; public class AIDLServiceTest extends Activity {
private static final String TAG = "skywang-->AIDLServiceTest"; private Button mStart = null;
private Button mHalf = null;
private Button mDouble = null;
private Button mEnd = null; private MyAIDLInterface mBinder = null;
private ServiceConnection mConnection = new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) {
mBinder = null;
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "Service connected!");
mBinder = MyAIDLInterface.Stub.asInterface(service);
}
}; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aidlservice_test); mStart = (Button) findViewById(R.id.btStart);
mStart.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View arg0) {
Log.d(TAG, "click start button"); Intent intent = new Intent("com.test.MY_AIDL_SERVICE");
boolean result = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
if (!result) {
mBinder = null;
}
}
}); mHalf = (Button) findViewById(R.id.btHalf);
mHalf.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View arg0) {
Log.d(TAG, "click half button"); try {
if (mBinder != null) {
mBinder.halfValue(10);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}); mDouble = (Button) findViewById(R.id.btDouble);
mDouble.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View arg0) {
Log.d(TAG, "click double button"); try {
if (mBinder != null) {
mBinder.doubleValue(10);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}); mEnd = (Button) findViewById(R.id.btEnd);
mEnd.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View arg0) {
Log.d(TAG, "click end button"); if (mBinder != null) {
unbindService(mConnection);
mBinder = null;
}
}
});
} }
3 示例演示
程序运行效果图:

点击“Start”按钮,Logcat如下:
DEBUG/skywang-->AIDLServiceTest(276):click half button
DEBUG/skywang-->AIDLServiceTest(276):Service connected!
点击“Half”按钮,Logcat如下:
DEBUG/skywang-->AIDLServiceTest(276):click half button
DEBUG/skywang-->MyAIDLService(285):halfValue val=5
点击“Double”按钮,Logcat如下:
DEBUG/skywang-->AIDLServiceTest(276):click double button
DEBUG/skywang-->MyAIDLService(285):doubleValue val=20
点击“End”按钮,Logcat如下:
DEBUG/skywang-->AIDLServiceTest(276):click end button
4 参考文献
1. Android API文档:http://developer.android.com/guide/components/aidl.html
2. Android AIDL使用详解:http://blog.csdn.net/stonecao/article/details/6425019
点击下载:源代码
更多service内容:
2 Android Service总结02 service介绍
3 Android Service总结03 之被启动的服务 -- Started Service
4 Android Service总结04 之被绑定的服务 -- Bound Service
5 Android Service总结05 之IntentService
Android Service总结06 之AIDL的更多相关文章
- Android Service和Binder、AIDL
1.首先理解service的作用和生命周期 由于activity如果切换,那么他就不再运行,那么我们想在玩游戏的时候听播放器中的音乐,activity就应运而生了,这是最常见的一种场景,同时servi ...
- Android Service总结05 之IntentService
Android Service总结05 之IntentService 版本 版本说明 发布时间 发布人 V1.0 添加了IntentService的介绍和示例 2013-03-17 Skywang ...
- Android Service总结04 之被绑定的服务 -- Bound Service
Android Service总结04 之被绑定的服务 -- Bound Service 版本 版本说明 发布时间 发布人 V1.0 添加了Service的介绍和示例 2013-03-17 Skywa ...
- Android Service总结01 目录
Android Service总结01 目录 1 Android Service总结01 目录 2 Android Service总结02 service介绍 介绍了“4种service 以及 它们的 ...
- Android Service总结02 service介绍
Android Service总结02 service介绍 版本 版本说明 发布时间 发布人 V1.0 介绍了Service的种类,常用API,生命周期等内容. 2013-03-16 Skywang ...
- Android Service总结03 之被启动的服务 -- Started Service
Android Service总结03 之被启动的服务 -- Started Service 版本 版本说明 发布时间 发布人 V1.0 添加了Service的介绍和示例 2013-03-17 Sky ...
- android service 的各种用法(IPC、AIDL)
http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...
- Android service binder aidl 关系
/********************************************************************************** * Android servic ...
- Android Service AIDL 远程调用服务 【简单音乐播放实例】
Android Service是分为两种: 本地服务(Local Service): 同一个apk内被调用 远程服务(Remote Service):被另一个apk调用 远程服务需要借助AIDL来完成 ...
随机推荐
- 基于 ARM的 Windows 10S 笔记本 转帖
首款骁龙笔记本华硕畅370评测:续航不俗 性能拖后腿 2018年06月21日 12:23 新浪数码 缩小字体放大字体收藏微博微信分享 相关阅读:国内首款骁龙本华硕畅370发布:6199元送一年无限 ...
- OneZero第五周第二次站立会议(2016.4.19)
1. 时间: 15:15--15:25 共计10分钟. 2. 成员: X 夏一鸣 * 组长 (博客:http://www.cnblogs.com/xiaym896/), G 郭又铭 (博客:http ...
- Java时间的转换
String DATE_FORMAT = "yyyy-MM-dd"; LocalDate localDate = LocalDate.now(); long startTime = ...
- 模拟事件【JavaScript高级程序设计第三版】
事件,就是网页中某个特别值得关注的瞬间.事件经常由用户操作或通过其他浏览器功能来触发.但很少有人知道,也可以使用JavaScript 在任意时刻来触发特定的事件,而此时的事件就如同浏览器创建的事件一样 ...
- bzoj 1798: [Ahoi2009]Seq 维护序列seq (线段树 ,多重标记下放)
1798: [Ahoi2009]Seq 维护序列seq Time Limit: 30 Sec Memory Limit: 64 MBSubmit: 7773 Solved: 2792[Submit ...
- IDEA导出jar包后运行报错 找不到或无法加载主类
开发工具:IDEA16 运行环境:ubuntu 问题:根据网上的Idea导出jar包的方法,将我的项目导出jar包后运行报错:找不到或无法加载主类. 为了找到这个原因,我重新搭建了一个测试例子,在 ...
- luogu1941 [NOIp2014]飞扬的小鸟 (dp)
设f[i][j]为到达(i,j)这个位置的最小操作数 就有$f[i][j]=min\{f[i-1][j+Y[i-1]],f[i-1][j-X[i-1]*k]+k\}$ 然后考虑优化一下转移: 对于一系 ...
- Request URI Too Long
如上图所示,URL传參长度限制,改为Post参数提交就好了.
- asp.net性能优化之使用Redis缓存(入门)
1:使用Redis缓存的优化思路 redis的使用场景很多,仅说下本人所用的一个场景: 1.1对于大量的数据读取,为了缓解数据库的压力将一些不经常变化的而又读取频繁的数据存入redis缓存 大致思路如 ...
- 质数——6N±1法
6N±1法求素数 任何一个自然数,总可以表示成为如下的形式之一: 6N,6N+1,6N+2,6N+3,6N+4,6N+5 (N=0,1,2,…) 显然,当N≥1时,6N,6N+2,6N+3,6N+4都 ...
