AIDL与Messenger跨进程通信

前言:

当初对于IPC跨进程通信技术感觉好"高大上",竟然还能在不同应用中通信。而android中的IPC机制,无论是AIDL还是Messenger都是通过Binder来进行跨进程通信的。

AIDL:由3个组件构成: 服务端接口,binder以及我们的客户端。服务端定义的IBinder接口,客户端通过通过ServiceConnection接收IBinder接口,然后执行IBinder接口中定义的方法,这样就是IPC的整个流程。如果对这整个流程不理解的,下面我们就通过一个例子来展示IPC。

一.服务端
1.建立.aidl文件:(这就相当于我们的服务端接口)
新建一个项目,创建一个包名为com.ljx.aidl的包,然后在这个包中新建一个后缀为.aidl的文件--DownLoad.aidl,void download(String path)就是我们服务端暴露给客户端的方法。
package com.ljx.aidl;
interface DownLoad{
	void download(String path);
}
然后clean一下我们的项目,Android SDK工具基于我们的.aidl文件使用java语言生成一个接口在我们的gen目录下 (这里用的eclipse,因为我项目都是用eclipse编写的,AS还不太会,不过我想应该也相差不大)。

下图就是我们的根据aidl生成的.java文件


2.定义一个我们的服务:
package com.example.myservices;

import com.ljx.aidl.DownLoad;

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

public class MyService extends Service{
	private static final String TAG = "MyService";
	
	//DownLoad.Stub 是我们gen目录下DownLoad.java接口中的一个内部抽象类,它继承Binder并实现我们的AIDL接口,
	//所以我们服务端必须实现这个Stub,并通过onBind()方法的回调返回给客户端
	//这样就实现了跨进程通信
	private DownLoad.Stub mBinder = new DownLoad.Stub() {
		
		@Override
		public void download(String path) throws RemoteException {
			// TODO Auto-generated method stub
			Log.d("EEEE", "通过客户端传来的路径:"+ path +"--开启线程下载数据");
		}
	};
	@Override
	public IBinder onBind(Intent arg0) {
		//把我们的Binder 传给客户端
		return mBinder;
	}


}

这里仅仅是个简单的demo,所以我们服务端的项目就仅仅只有一个Service.
下面是我们的AndroidMainfest.xml文件的代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <service android:name=".MyService" >
            <intent-filter>
                <action android:name="ljx.service.test"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>
    </application>

</manifest>

好了我们服务端就构建完成了,接下来就是我们的客户端了

二.客户端:
1.把我们的com.ljx.aidl这个包复制到我们的客户端项目下

2.客户端Mainactivity

package com.example.mycilentforaidl;

import com.ljx.aidl.DownLoad;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends Activity {
	private DownLoad download;
	
	private boolean isConn;
	
	private ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			download = null;
			isConn = false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, "OnBinding", 0).show();
			//通过Stub的asInterface()方法返回我们的Download实例,有兴趣的可以看下DownLoad.java文件
			download = DownLoad.Stub.asInterface(service);
			isConn = true;
		}
	};
	
	//在onstart中绑定我们的服务
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent();
		intent.setAction("ljx.service.test");
		//通过传入conn绑定我们的服务,在conn的onServiceConnected回调中返回我们服务onBind()中返回的Binder
		bindService(intent, conn, BIND_AUTO_CREATE);
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void downLoad(View v){
    	//如果服务绑定成功
    	if(isConn){
    		try {
				download.download("http:......"); 
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	unbindService(conn);
    }
}
客户端Activity的布局代码的代码:
<RelativeLayout 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: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.example.mycilentforaidl.MainActivity" >
	
    <Button
        android:onClick="downLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="BindService" />

</RelativeLayout>

这样就实现了我们IPC,接下来就进行测试,看我们的IPC是否成功
先运行我们的服务,然后再运行我们的客户端程序-------

额,把歌词也录进去了,哈哈。可以看到我们在onstart()中绑定的服务,根据Toast提示我们的服务绑定成功了然后再看我们在服务中打印的Log,看点击button是否执行了download().


由我们的Log日志看出,我们点击客户端的button,确实是执行了我们服务中声明的download()。
这样我们就实现IPC。(PS:如果想更详细的了解AIDL机制,可以查看android官方文档。)

Messenger实现IPC:
其实Messenger内部也是使用的AIDL机制,只是google工程师为我们做了封装,源码我这里就不详细叙述了,想了解的可以自己去看下,内部代码很容易理解的,这里只是分析用法。

使用Messenger实现IPC原理:
如果你需要接口跨越多个进程进行工作,可以通过 Messenger来为服务创建接口。在这种方式下,服务定义一个响应各类消息对象 MessageHandler。此 HandlerMessenger与客户端共享同一个 IBinder的基础,它使得客户端可以用消息对象 Message向服务发送指令。此外,客户端还可以定义自己的 Message,以便服务能够往回发送消息。
这是执行进程间通信(IPC)最为简便的方式,因为 Messenger会把所有的请求放入一个独立进程中的队列,这样你就不一定非要把服务设计为线程安全的模式了。(以上文档由android官方文档翻译而来,我觉得这段话简单明了的阐述的Messenger实现IPC原理,所以就直接引用来了)
使用Messenger来实现IPC相对而言要简单的多,废话不多说,直接上代码
1.服务端

这里也仅仅只是定义一个服务
服务类的代码:
package com.example.messengerservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Messenger;
import android.widget.Toast;

public class SayHelloService extends Service {

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msgFromCilent) {
			switch (msgFromCilent.what) {
			case 1:
				Toast.makeText(getApplicationContext(), "hello world", 0).show();;
				break;

			}
			super.handleMessage(msgFromCilent);
		};
	};
	private Messenger mMessenger = new Messenger(mHandler);

	@Override
	public IBinder onBind(Intent intent) {
		Toast.makeText(getApplicationContext(), "service onbinding", 0).show();
		return mMessenger.getBinder();
	}

}

可以看出我们服务端仅仅是通过Handler来接收一个消息,通过消息中what的值来执行我们服务中定义的方法
服务端的AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.messengerservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <service android:name=".SayHelloService" >
            <intent-filter>
                <action android:name="com.ljx.test" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>
    </application>

</manifest>

2.客户端

MainActivity代码:
package com.example.messengercilent;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;


public class MainActivity extends Activity {
	private boolean isConn;
	private Messenger mService;
	
	private ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			isConn = false;
			mService = null;
		} 
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			isConn = true;
			//这里通过绑定服务成功后,服务端的onBind()方法返回的Ibinder对象,构建我们客户端的Messenger
			mService = new Messenger(service);
			
		}
	};
	
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent();
		intent.setAction("com.ljx.test");
		bindService(intent, conn, BIND_AUTO_CREATE);
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	public void bind(View v){
		if(isConn){
			Message msgFromCilent = Message.obtain(null, 1, 0, 0);
			try {
				mService.send(msgFromCilent);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	} 
}

而客户端这里也仅仅是构建一个Messenger来发送消息,然后服务端接收,整个过程就相当于一个消息机制。
客户端的布局代码:
<RelativeLayout 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: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.example.messengercilent.MainActivity" >

    <Button
        android:onClick="bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bindService" />

</RelativeLayout>
由上面的代码看出,通过Messenger来实现IPC相对于通过AIDL还是较简单的,所以我这里就不做详细的分析了,案例也是来自android 官方文档, 当然通过Messenger还可以实现服务端与客户端之间的互相通信,服务端发送消息,客户端接受,客户端发送消息,服务端接收,相信熟悉消息机制的同学肯定能熟练掌握。这个我这里就不做实现了,如果想深入学习的可以自行了解。
最后就来测试下我们的代码,看通过Messenger实现IPC是否成功:这里也是先运行服务,然后再执行客户端代码


好了,AIDL和Messenger实现IPC机制就介绍这里。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值