Android aidl通信详解

前段时间研究了不少android二次开发,其中有一种方法就是通过aidl通信,留接口提供给外面二次开发。从这里也可以看出:aidl通信是两个应用程序之间的进程通信了。在这篇博客中,主要写了两个应用程序,一个是serverdemo,可以称为服务端,也是提供接口的应用程序,在这里面我写了一个加法计算。二是客户端:clientdemo,在这个程序中调用了加法计算接口,把值传到serverdemo进行加法计算,返回结果,进行显示。

1、aidl的定义

aidl是 Android Interface
definition language的缩写,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口;icp:interprocess communication :内部进程通信。

2、两个项目结构以及实现效果

 

 

从上面图中看以大概看出,服务端布局什么都没有,不过这里面有加法计算的服务。而客户端有两个输入框输入两个值,点击计算。

3、server服务端

3.1、新建创建你的aidl文件

保存你的aidl文件,这个只要是在eclipse中开发,你的adt插件会像资源文件一样把aidl文件编译成java代码生成在gen文件夹下,不用手动去编译:编译生成AIDLService.java如我例子中代码。

IBoardADDInterface.aidl

package com.example.server;
import android.os.Bundle;

/***
 * System private API for talking with the caculate service.
 *
 * {@hide}
 */
interface IBoardADDInterface
{
    int add(int nValue1,int nValue2);
}

自动把aidl文件编译成java代码生成在gen文件夹下IBoardADDInterface的接口代码

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: C:\\Users\\southgnssliyc\\Desktop\\android aidl\\ServerDemo\\src\\com\\example\\server\\IBoardADDInterface.aidl
 */
package com.example.server;
/***
 * System private API for talking with the caculate service.
 *
 * {@hide}
 */
public interface IBoardADDInterface extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.example.server.IBoardADDInterface
{
private static final java.lang.String DESCRIPTOR = "com.example.server.IBoardADDInterface";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
 * Cast an IBinder object into an com.example.server.IBoardADDInterface interface,
 * generating a proxy if needed.
 */
public static com.example.server.IBoardADDInterface asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.example.server.IBoardADDInterface))) {
return ((com.example.server.IBoardADDInterface)iin);
}
return new com.example.server.IBoardADDInterface.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_add:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
int _result = this.add(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.example.server.IBoardADDInterface
{
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 int add(int nValue1, int nValue2) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(nValue1);
_data.writeInt(nValue2);
mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}
public int add(int nValue1, int nValue2) throws android.os.RemoteException;
}

这代码一看就是自动生成的。

3.2、服务端的计算加法实现类,写一个server

package com.example.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

/**
 * 服务端的计算加法实现类
 * @author mmsx
 *
 */
public class CaculateAddService extends Service {
	//加法计算的服务
	final String CACULATE_ADD = "COM.CACULATE.ADD";

	//找到自定义服务
	@Override
	public IBinder onBind(Intent intent) {
		if(intent.getAction().equals(CACULATE_ADD))
		{
			return mIBinder_CACULATE_ADD;
		}
		return null;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	//aidl的接口实现
	private final IBinder mIBinder_CACULATE_ADD = new IBoardADDInterface.Stub()
	{

		@Override
		public int add(int nValue1, int nValue2) throws RemoteException {
			Log.i("Show", String.valueOf(nValue1) + ",,," +String.valueOf(nValue2));
			return nValue1 + nValue2;
		}

	};
}

既然你写了一个service,那么就要在AndroidManifest.xml中添加注册

        <service android:name="com.example.server.CaculateAddService" >
            <intent-filter>
                <action android:name="COM.CACULATE.ADD" >
                </action>
            </intent-filter>
        </service>

这个名称是自定义的:COM.CACULATE.ADD。service的路径com.example.server.CaculateAddService。

到这里就写完了这个服务端的应用程序,是不是很简单。activity都没写什么,因为只是用到里面的一个service和aidl。

4、客户端client

4.1、把服务端的aidl拷到客户端,代码不变

package com.example.server;
import android.os.Bundle;

/***
 * System private API for talking with the caculate service.
 *
 * {@hide}
 */
interface IBoardADDInterface
{
    int add(int nValue1,int nValue2);
}

自动编译生成的代码就不贴了。

.4.2、写一个绑定计算服务的类CaculateManager

package com.example.clientdemo;

import com.example.server.IBoardADDInterface;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * 客户端的服务计算管理类
 * @author mmsx
 *
 */
public class CaculateManager {
	//加法计算的服务
	final String CACULATE_ADD = "COM.CACULATE.ADD";

	//aidi接口服务
	IBoardADDInterface mService = null;

    /***
     * 服务绑定
     */
    public void bindService(Context context) {
    	mContext = context;
    	context.bindService(new Intent(CACULATE_ADD),
				serviceConnection, Context.BIND_AUTO_CREATE);
    }

    Context mContext = null;

    /***
    * 解除服务绑定
    */
    public void unbindService()
    {
    	if (mContext != null) {
    		mContext.unbindService(serviceConnection);
		}
    }

    /**
     * 加法计算
     * @param nValue1
     * @param nValue2
     * @return 结果
     */
    public int caculateAdd(int nValue1,int nValue2)
    {
		if (mService == null)
			return 0;

		try {
			return mService.add(nValue1, nValue2);
		} catch (Exception e) {
			return 0;
		}
    }

    //服务和aidl接口绑定
    private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = IBoardADDInterface.Stub.asInterface(service);
		}
	};
}

这里面有找到服务,解除服务。方法实现的接口。

4.3、activity输入数据,调用接口

package com.example.clientdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	CaculateManager caculateManager = new CaculateManager();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		caculateManager.bindService(this);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EditText editText1 = (EditText)findViewById(R.id.editText1);
				EditText editText2 = (EditText)findViewById(R.id.editText2);
				int nValue1 = Integer.parseInt(editText1.getText().toString().trim());
				int nValue2 = Integer.parseInt(editText2.getText().toString().trim());
				int nResult = caculateManager.caculateAdd(nValue1, nValue2);

				TextView textView = (TextView)findViewById(R.id.textView1);
				textView.setText("计算结果:" + String.valueOf(nResult));
			}
		});
	}

}

xml代码很简单

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用aidi服务调用其他程序计算,返回结果" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="计算结果:" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加法计算" />

</LinearLayout>

最后,本文的博客代码:下载

时间: 2024-08-01 02:47:42

Android aidl通信详解的相关文章

Android AIDL使用详解

1.什么是aidl:aidl是 Android Interface definition language的缩写,一看就明白,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口 icp:interprocess communication :内部进程通信 2.既然aidl可以定义并实现进程通信,那么我们怎么使用它呢?文档/android-sdk/docs/guide/developing/tools/aidl.html中对步骤作了详细描述: --1.Create

Android AIDL使用详解_Android IPC 机制详解

一.概述 AIDL 意思即 Android Interface Definition Language,翻译过来就是Android接口定义语言,是用于定义服务器和客户端通信接口的一种描述语言,可以拿来生成用于IPC的代码.从某种意义上说AIDL其实是一个模板,因为在使用过程中,实际起作用的并不是AIDL文件,而是据此而生成的一个IInterface的实例代码,AIDL其实是为了避免我们重复编写代码而出现的一个模板 设计AIDL这门语言的目的就是为了实现进程间通信.在Android系统中,每个进程

Android蓝牙通信详解

蓝牙通信的大概步骤如下: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 还要发送配对码发送进行判断! 下面是所有的源代码:不会很难:认真看: SearchDeviceActivity.java [java] view plaincopy package com.hello.project; import java.util.ArrayList; import java.util.Iterator; import java.

Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解

Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解 (本文转自: http://blog.csdn.net/yinhaide/article/details/44756989) 前言:现在很多APP都需要云的功能,也就是通过网络与服务器交换数据.有的采用tcp/ip协议,但是你必须拥有一个固定ip的服务器,可以购买阿里云服务器之类的,就是贵了点.如果只是个人的小应用的的话可以采用新浪云平台这种免费的服务器,采用的协议是http协议,具体实现方式如下: 方式一.在线

Android Service使用详解

Service是Android系统中的四大组件之一,主要有两个应用场景:后台运行和跨进程访问.Service可以在后台执行长时间运行操作而不提供用户界面,除非系统必须回收内存资源,否则系统不会停止或销毁服务.服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行. 此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信 (IPC) 需要注意的是,Service是在主线程里执行操作的,可能会因为执行耗时操作而导致ANR 一.基础知识 Service可以分为以下三种形式

Android 四大组件 详解

[置顶] Android四大组件详解 分类: Android四大组件2013-02-09 16:23 19411人阅读 评论(13) 收藏 举报 Android开发 注:本文主要来自网易的一个博主的文章,经过阅读,总结,故留下文章在此 Android四大基本组件介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器. 一:了解四大基本组件 Activity : 应用程序中,一个

Android BroadcastReceiver基础详解一

-.BroadcastReceivcer概述 1.什么是广播 BroadcastReceiver是Android四大组件之一,本质是一种全局的监听器,用于监听系统全局的广播消息.因此它可以非常方便的实现不同组件之间的通信. 2.BroadcastReceiver的创建启动 BroadcastReceiver是用用于接受程序所放出的Broadcast Intent,与应用程序启动的Activity.Service相同.也只需要两步: ①.创建需要启动的Broadcast的Intent ②.创建一个

Android GLSurfaceView用法详解(二)

输入如何处理       若是开发一个交互型的应用(如游戏),通常需要子类化 GLSurfaceView,由此可以获取输入事件.下面有个例子: java代码: package eoe.ClearTest; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.app.Activity; import android.conte

Android SDK Manager详解

Android基础知识--Android SDK Manager详解 做Android开发时,免不了使用Android SDK Manager,安装需要的sdk版本.buildTools版本等等. 下图展示了2016.11.16号Android SDK Manager所有的package.很多Android开发的新人在使用的时候可能会疑惑了:这些package到都是什么功能呢,都要安装吗?本篇文章将为你把这些疑惑解开(如果你只想知道需要安装哪些package,直接跳至文末). 1. SDK Ma