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>

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


猜你喜欢

转载自blog.csdn.net/qq_16064871/article/details/51385691