初学Android,跨进程调用Service(六十)

Android系统中,各应用程序都运行在自己的进程中,进程之间一般无法进行数据交换。
Android调用Service先定义一个远程调用接口,然后为该接口提供一个实现类。

Android访问Service时,不是直接返回Service对象给客户端——Service只是将一个回调对象(IBinder对象)通过onBind()方法返回给客户端。因此Android的AIDL远程接口的实现类就是那个IBinder实现类。

与绑定本地Service不同的是,本地Service的onBind()方法会直接把Service对象本身传给可uhuduandeServiceConnection的onServiceConnected方法的第二个参数。而远程Service的onBind()方法只是将IBinder对象的代理传给客户端的ServiceConnection的onServiceConnected方法的第二个参数。
当客户端获取远程Service的IBinder的对象的代理之后,接下来就可以通过该IBinder对象去回调远程Service的属性或方法了。
Android用AIDL(Android Interface Definition Language)来定义远程接口。
AIDL这种接口定义语言不是一种真正的编程语言,它只是定义两个进程间的通信接口。
AIDL定义接口的源代码必须以.aidl结尾。
AIDL接口中用到数据类型,除了基本类型、String、List、Map、CharSequence之外,其他类型都需要导入包,即使它们在同一个包中也需要导包。

定义一个.aidl文件

File->New->File,然后输入文件存放的路径,和文件名(比如Itest.aidl).然后在弹出的文件编辑界面输入包名和一个接口定义,保存好就可以了

ICat.aidl

package WangLi.Service.AidlService;
interface ICat
{
    String getColor();
    double getWeight();
}
创建完毕后,eclipse会自动在gen文件夹下创建ICat.java

每个根据.aidl文件自动生成接口中(上面的ICat)中都会包含一个静态类stub.

下面的代码就是在gen文件夹下跟据.aidl自动生成的

package WangLi.Service.AidlService;

public interface ICat extends android.os.IInterface {
	/** Local-side IPC implementation stub class. */
	public static abstract class Stub extends android.os.Binder implements
			WangLi.Service.AidlService.ICat {
		private static final java.lang.String DESCRIPTOR = "WangLi.Service.AidlService.ICat";

		/** Construct the stub at attach it to the interface. */
		public Stub() {
			this.attachInterface(this, DESCRIPTOR);
		}

		/**
		 * Cast an IBinder object into an WangLi.Service.AidlService.ICat
		 * interface, generating a proxy if needed.
		 */
		public static WangLi.Service.AidlService.ICat 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 WangLi.Service.AidlService.ICat))) {
				return ((WangLi.Service.AidlService.ICat) iin);
			}
			return new WangLi.Service.AidlService.ICat.Stub.Proxy(obj);
		}
......

WangLi.Service.AidlService.ICat asInterface()这个方法回返回一个Binder代理对象

下面定义一个Service,已实现上面的AIDL接口,该Service的onBinde()方法所返回的IBinder对象应该是ADT所生成的ICat.Stub的子类的实例,其它部分则与开发本地Service完全一样.

package WangLi.Service.AidlService;

import java.util.Timer;
import java.util.TimerTask;

import WangLi.Service.AidlService.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;

	// 继承Stub,也就是实现了ICat接口,并实现了IBinder接口 
	public class CatBinder extends Stub {
		@Override
		public String getColor() throws RemoteException {
			return color;
		}

		@Override
		public double getWeight() throws RemoteException {
			return weight;
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		catBinder = new CatBinder();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				// 随机改变Service组件内color,weight属性的值
				int rand = (int) (Math.random() * 3);
				color = colors[rand];
				weight = weights[rand];
				System.out.println("--------" + rand);
			}
		}, 0, 800);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		/*
		 * 返回catBinder对象在绑定本地Service的情况下,
		 * 该catBinder对象会直接传给客户端的ServiceConnection对象的 onServiceConnected方法的第二个参数;
		 * 在绑定远程Service的情况下,只将catBinder对象的代理传给客户端的
		 * ServiceConnection对象的onServiceConnected方法的第二个参数
		 */
		return catBinder;
	}
	
	@Override
	public void onDestroy() {
		timer.cancel();
	}
}

上面的项目由于没有Activity,没有任何界面,所以在程序列表中看不到这个应用.

定义后这个Service后,别忘了在AndroidManifest.xml文件中增加它的配置

        <service android:name=".AidlService">
            <intent-filter>
                <action android:name="WangLi.Service.Aidl_Service"></action>
            </intent-filter>
        </service>

下面定义一个客户端项目来访问这个Service


package WangLi.Service.AidlClient;

import WangLi.Service.AidlService.ICat;
import android.app.Activity;
import android.app.Service;
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.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 onServiceConnected(ComponentName name, IBinder service)
		{
			// 获取远程Service的onBind方法返回的对象的代理
			catService = ICat.Stub.asInterface(service);
		}

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

	@Override
	public void onCreate(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);
		// 创建所需绑定服务的Intent
		Intent intent = new Intent();
		intent.setAction("WangLi.Service.Aidl_Service");
		// 绑定远程服务
		bindService(intent, conn, Service.BIND_AUTO_CREATE);
		get.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				try
				{
					// 获取、并显示远程Service的状态
					color.setText(catService.getColor());
					weight.setText(catService.getWeight() + "");
				}
				catch (RemoteException e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		// 解除绑定
		this.unbindService(conn);
	}
}


要注意这个方法:

// 获取远程Service的onBind方法返回的对象的代理
catService = ICat.Stub.asInterface(service);



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值