我们都知道在Android中的每一个应用是一个进程,其实每一个应用就相当于Linux系统里面的一个用户,进程和进程之间的通信其实就相当于用户和用户之间的通信,为了实现这种跨进程通信,Android提供了AIDL Service (Android Interface definition language).
与邦等本地Service不同的是,本地Service的onBind()方法会直接把IBinder对象本身传给客户端的ServiceConnection的onServiceConnected方法的第二个参数。但远程Service的onBind()方法只是将IBinder对象的代理传给客户端的ServiceConnection的onService Connected方法的第二个参数。
ALDL定义的特点:
1、AIDL定义接口的源码必须以.aidl结尾。
2、AIDL接口中用到数据类型,除了基本类型、String、List、Map、CharSequence之外,其他类型全部都需要导包,即使它们在同一个包中也需要导包。
下面来具体实现一个示例:
(1)定义AIDL接口(和Java接口非常类似)
package com.example.testservice;
interface ICat {
String getColor();
double getWeight();
}
(2)定以好上面接口后保存,ADT工具会自动在gen.com.example.service目录下生成一个ICat.jar接口,在该接口中包含一个Stub内部类,该内部类实现了IBinder、ICat两个接口,这个Stub类将会作为远程Service的回调类——它实现了IBuilder接口,因此可作为Service的onBind()方法的返回值。这个Stub类就是一个代理类,同样可以实现IBinder的功能,并且还额外实现了ICat远程访问的功能。
自动生成的ICat.java接口
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: D:\\adt-bundle-windows-x86-20130729\\eclipse\\workspace\\TestService\\src\\com\\example\\testservice\\ICat.aidl
*/
package com.example.testservice;
public interface ICat extends android.os.IInterface {
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements
com.example.testservice.ICat {
private static final java.lang.String DESCRIPTOR = "com.example.testservice.ICat";
/** Construct the stub at attach it to the interface. */
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.example.testservice.ICat
* interface, generating a proxy if needed.
*/
public static com.example.testservice.ICat asInterface(
android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.example.testservice.ICat))) {
return ((com.example.testservice.ICat) iin);
}
return new com.example.testservice.ICat.Stub.Proxy(obj);
}
@Override
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_getColor: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _result = this.getColor();
reply.writeNoException();
reply.writeString(_result);
return true;
}
case TRANSACTION_getWeight: {
data.enforceInterface(DESCRIPTOR);
double _result = this.getWeight();
reply.writeNoException();
reply.writeDouble(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.example.testservice.ICat {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
@Override
public java.lang.String getColor()
throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.lang.String _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getColor, _data, _reply,
0);
_reply.readException();
_result = _reply.readString();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public double getWeight() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
double _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getWeight, _data, _reply,
0);
_reply.readException();
_result = _reply.readDouble();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_getColor = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_getWeight = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public java.lang.String getColor() throws android.os.RemoteException;
public double getWeight() throws android.os.RemoteException;
}
(3)定义一个Service实现类,该Service的onBind()方法所返回的IBinder对象应该是ADT所生成的ICat.Stub的子类的实例。这一步的主要作用是将上面创建的接口暴漏给客户端。
package com.example.testservice;
import java.util.Timer;
import java.util.TimerTask;
import com.example.testservice.ICat.Stub;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AidlService extends Service{
private CatBinder catBinder;
Timer timer = new Timer();
String[] colors = new String[]{
"红色",
"黄色",
"黑色"
};
double[] weights = new double[]{
2.3,
3.1,
1.58
};
private String color;
private double weight;
@Override
public IBinder onBind(Intent intent) {
/*
* 返回catBinder对象
* 在绑定本地Service的情况下,该catBinder对象会直接传给客户端的
* ServiceConnection对象的onServiceConnected方法的第二个参数;
* 在绑定远程Service的情况下,只将catBinder对象的代理传给客户端的
* ServiceConnection对象的onServiceConnected方法的第二个参数;
*/
return catBinder;
}
//继承Stub,也就是实现了ICat接口,并实现了IBinder接口
public class CatBinder extends Stub{
@Override
public String getColor() throws RemoteException {
// TODO Auto-generated method stub
return color;
}
@Override
public double getWeight() throws RemoteException {
// TODO Auto-generated method stub
return weight;
}
}
@Override
public void onCreate() {
super.onCreate();
catBinder = new CatBinder();
timer.schedule(new TimerTask() {
@Override
public void run() {
int rand = (int)(Math.random() * 3);
color = colors[rand];
weight = weights[rand];
System.out.println("---------" + rand);
}
}, 0, 800);
}
}
(4)在AndroidMainfest.xml文件中配置该Service
<service android:name=".AidlService">
<intent-filter>
<action android:name="com.example.testservice.action.AIDL_SERVICE"/>
</intent-filter>
</service>
(5)客户端访问AIDL Service
上面说过AIDL是定义在两个进程之间通信的一个接口,既然是一个通信协议,客户端同样需要前面定义的AIDL接口,所以第一步就是将AIDL文件复制到客户端应用中。
package com.example.testservice;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
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;
public class AidlClient extends Activity{
private ICat catService;
private Button get;
EditText color, weight;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取远程Service的onBind方法返回的对象的代理
catService = ICat.Stub.asInterface(service);
}
};
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
get = (Button)findViewById(R.id.get);
color = (EditText)findViewById(R.id.color);
weight = (EditText)findViewById(R.id.weight);
//创建所需绑定的Service的Intent
Intent intent = new Intent();
intent.setAction("com.example.testservice.action.AIDL_SERVICE");
bindService(intent, conn, Service.BIND_AUTO_CREATE);
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
color.setText(catService.getColor());
weight.setText(catService.getWeight() + "");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
};
@Override
protected void onDestroy() {
super.onDestroy();
//解除绑定
this.unbindService(conn);
}
}
下一篇将介绍如何在进程之间传递复杂数据
分享到:
相关推荐
android服务自启动Service以及BroadcastReceiver和Notification.zip
Android Service与BroadcastReceiver、bindService示例详解,代码非常详细,详解博客网址:http://blog.csdn.net/sunboy_2050/article/details/7364024
Android应用程序的四大组件中Activity、BroadcastReceiver、ContentProvider、Service都可以进行跨进程。在上一篇我们通过ContentProvider实现了不同应用之间的跨进程调用,但ContentProvider主要是提供数据的共享...
android service Notification BroadcastReceiver Intent 安装的服务开机自启动,service定时的打印消息,消息同时显示在通知栏,窗体界面的跳转,自定义控件的开发。系统广播,定时广播,轮询广播等。...
BroadcastReceiver——Android四大组件只一——广播
对应于博客中的例子: 有:定时任务,发送短信,状态栏通知,行车模式,夜间模式,唤醒锁,音量设置, 开机自启设置,拍照设置,等
初中级Android开发社招面试之Service及BroadcastReceiver
初中级Android开发社招面试之Service及BroadcastReceiver
先启动service 然后最后一个按钮
这是一个关于Android中四大组件之一 —— BroadcastReceiver,即广播的一个demo,里面涉及到BroadcastReceiver的两种注册方式,也简单的实现了广播,通过点击按钮发送广播,收到广播后打印日志。
demo中service使用得是新的进程,activity和service日志需要切换进程才能看到,这里是最典型得activity和service交互的过程, activity传递信息很简单,通过startService并传递intent即可,但是service却只能通过广播的...
NULL 博文链接:https://wilian.iteye.com/blog/966475
Android:Intent页面跳转,Activity生命周期,Service服务,广播代码实例
安卓四大组件——BroadcastReceiver(广播)
10.2 跨进程调用Service (AIDL服务) 382 10.2.1 AIDL服务简介 382 10.2.2 创建AIDL文件 383 10.2.3 将接口暴露给客户端 383 10.2.4 客户端访问AIDLService 385 10.3 电话管理器 ...
Service与BroadcastReceiver的联合应用。
服务主要用于两个目的:后台运行和跨进程访问。通过启动一个服务,可以在不显示界面的前提下在后台运行指定的任务,这样可以不影响用户做其他事情。通过AIDL服务可以实现不同进程之间的通信,这也是服务的重要用途之...