Android四大组件之Service:远程service

远程service

AIDL

每个应用程序都运行在自己的独立进程中,
并且可以启动另一个应用进程的服务,
而且经常需要在不同的进程间传递数据对象。

在Android平台,一个进程不能直接访问另一个进程的内存空间,
所以要想对话,需要将对象分解成操作系统可以理解的基本单元(例如基本数据类型),
并且有序的通过进程边界。
AIDL (Android Interface Definition Language) 
	用于生成可以在Android设备上两个进程之间
	进行进程间通信(interprocess communication, IPC)的代码。

如果在一个进程中(例如Activity)要调用另一个
进程中(例如Service)对象的操作,就可以使用AIDL生成可序列化的参数。

练习例子

首先定义AIDL接口
这个AIDL接口和接口的类很像,我们可以先定义一个这样的接口
然后再进行适当的修改就可以了

创建文件:IStudentService.aidl

	package com.example.service;
	import com.example.service.Student;
	interface IStudentService 
	{
		Student getStudentById(int id);
	}

编写AIDL需要注意:
1.接口名和aidl文件名相同.
2.接口和方法前不用加访问权限修饰符public,private,protected等,也不能用final,static.
3.aidl默认支持的类型包话java基本类型(int,long,boolean等)和(String,List,Map,CharSequence),
	使用这些类型时不需要import声明.对于List和Map中的元素类型必须是aidl支持的类型.
	如果使用自定义类型作为参数或返回值,自定义类型必须实现Parcelable接口.
4.自定义类型和aidl生成的其它接口类型在aidl描述文件中,应该显式import,
	即便在该类和定义的包在同一个包中.
5.在aidl文件中所有非Java基本类型参数必须加上in、out、inout标记,
	以指明参数是输入参数、输出参数还是输入输出参数.
6.Java原始类型默认的标记为in,不能为其它标记.
然后创建自定义类型Student

package com.example.service;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Student implements Parcelable
{

	private int id;
	private String name;
	private double price;

	@Override
	public int describeContents()
	{
		return 0;
	}
	
	// 将当前对象的属性数据打成包: 写到包对象中
	@Override
	public void writeToParcel(Parcel dest, int flags)
	{
		Log.e("TAG", "打包 writeToParcel()");
		// id
		dest.writeInt(id);
		// name
		dest.writeString(name);
		// price
		dest.writeDouble(price);
	}
	
	// 添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口
	public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>()
	{
		
		// 解包: 读取包中的数据并封装成对象
		@Override
		public Student createFromParcel(Parcel source)
		{
			Log.e("TAG", "解包 createFromParcel()");
			// id
			int id = source.readInt();
			// name
			String name = source.readString();
			// price
			double price = source.readDouble();
			
			return new Student(id, name, price);
		}
		
		// 返回一个指定大小的对象容器
		@Override
		public Student[] newArray(int size)
		{
			return new Student[size];
		}
	};
	
	public Student(int id, String name, double price)
	{
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public Student()
	{
		super();
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public double getPrice()
	{
		return price;
	}

	public void setPrice(double price)
	{
		this.price = price;
	}

	@Override
	public String toString()
	{
		return "Student [id=" + id + ", name=" + name + ", price=" + price+ "]";
	}
}
然后定义自定义类型的AIDL接口 

创建文件:Student.aidl

package com.example.service;
parcelable Student;
然后会自动生成一个通信接口类
粘出来给看看吧

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: E:\\Android\\WorkSpace\\Service\\src\\com\\example\\service\\IStudentService.aidl
 */
package com.example.service;

public interface IStudentService extends android.os.IInterface
{
	/** Local-side IPC implementation stub class. */
	public static abstract class Stub extends android.os.Binder implements
			com.example.service.IStudentService
	{
		private static final java.lang.String DESCRIPTOR = "com.example.service.IStudentService";

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

		/**
		 * Cast an IBinder object into an com.example.service.IStudentService
		 * interface, generating a proxy if needed.
		 */
		public static com.example.service.IStudentService asInterface(
				android.os.IBinder obj)
		{
			if ((obj == null))
			{
				return null;
			}
			android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
			if (((iin != null) && (iin instanceof com.example.service.IStudentService)))
			{
				return ((com.example.service.IStudentService) iin);
			}
			return new com.example.service.IStudentService.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_getStudentById:
			{
				data.enforceInterface(DESCRIPTOR);
				int _arg0;
				_arg0 = data.readInt();
				com.example.service.Student _result = this
						.getStudentById(_arg0);
				reply.writeNoException();
				if ((_result != null))
				{
					reply.writeInt(1);
					_result.writeToParcel(reply,
							android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
				} else
				{
					reply.writeInt(0);
				}
				return true;
			}
			}
			return super.onTransact(code, data, reply, flags);
		}

		private static class Proxy implements
				com.example.service.IStudentService
		{
			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 com.example.service.Student getStudentById(int id)
					throws android.os.RemoteException
			{
				android.os.Parcel _data = android.os.Parcel.obtain();
				android.os.Parcel _reply = android.os.Parcel.obtain();
				com.example.service.Student _result;
				try
				{
					_data.writeInterfaceToken(DESCRIPTOR);
					_data.writeInt(id);
					mRemote.transact(Stub.TRANSACTION_getStudentById, _data,
							_reply, 0);
					_reply.readException();
					if ((0 != _reply.readInt()))
					{
						_result = com.example.service.Student.CREATOR
								.createFromParcel(_reply);
					} else
					{
						_result = null;
					}
				} finally
				{
					_reply.recycle();
					_data.recycle();
				}
				return _result;
			}
		}

		static final int TRANSACTION_getStudentById = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
	}

	public com.example.service.Student getStudentById(int id)
			throws android.os.RemoteException;
}
下一步是:
	在Service类中使用生成的类实现业务方法
	
package com.example.service;

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

public class MyRemoteService extends Service
{

	@Override
	public IBinder onBind(Intent intent)
	{
		Log.e("TAG", "onBind()");
		return new StudentService();
	}

	@Override
	public boolean onUnbind(Intent intent)
	{
		Log.e("TAG", "onUnbind()");
		return super.onUnbind(intent);
	}

	// 处理Student相关的业务逻辑类
	class StudentService extends IStudentService.Stub
	{
		@Override
		public Student getStudentById(int id) throws RemoteException
		{
			Log.e("TAG", "Service getStudentById() " + id);
			return new Student(id, "jane", 10000000);
		}
	}

}
然后再到客户端进行编码的了
首先复制服务端AIDL的相关定义
自动生成一个通信接口类
在Activity中bind远程Service,并调用业务方法

	public void bindRemoteService(View v)
	{

		Intent intent = new Intent("com.example.service.MyRemoteService.Action");
		if (conn == null)
		{
			conn = new ServiceConnection()
			{
				@Override
				public void onServiceDisconnected(ComponentName name)
				{

				}

				@Override
				public void onServiceConnected(ComponentName name,IBinder service)
				{
					Log.e("TAG", "onServiceConnected()");
					studentService = IStudentService.Stub.asInterface(service);
				}
			};
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
			Toast.makeText(this, "绑定Service", 0).show();
		} else
		{
			Toast.makeText(this, "已经绑定Service", 0).show();
		}
	}

到这里是终于结束了

总的代码

服务端
package com.example.service;

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

public class MyRemoteService extends Service
{

	@Override
	public IBinder onBind(Intent intent)
	{
		Log.e("TAG", "onBind()");
		return new StudentService();
	}

	@Override
	public boolean onUnbind(Intent intent)
	{
		Log.e("TAG", "onUnbind()");
		return super.onUnbind(intent);
	}

	// 处理Student相关的业务逻辑类
	class StudentService extends IStudentService.Stub
	{
		@Override
		public Student getStudentById(int id) throws RemoteException
		{
			Log.e("TAG", "Service getStudentById() " + id);
			return new Student(id, "jane", 10000000);
		}
	}

}

package com.example.service;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Student implements Parcelable
{

	private int id;
	private String name;
	private double price;

	@Override
	public int describeContents()
	{
		return 0;
	}
	
	// 将当前对象的属性数据打成包: 写到包对象中
	@Override
	public void writeToParcel(Parcel dest, int flags)
	{
		Log.e("TAG", "打包 writeToParcel()");
		// id
		dest.writeInt(id);
		// name
		dest.writeString(name);
		// price
		dest.writeDouble(price);
	}
	
	// 添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口
	public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>()
	{
		
		// 解包: 读取包中的数据并封装成对象
		@Override
		public Student createFromParcel(Parcel source)
		{
			Log.e("TAG", "解包 createFromParcel()");
			// id
			int id = source.readInt();
			// name
			String name = source.readString();
			// price
			double price = source.readDouble();
			
			return new Student(id, name, price);
		}
		
		// 返回一个指定大小的对象容器
		@Override
		public Student[] newArray(int size)
		{
			return new Student[size];
		}
	};
	
	public Student(int id, String name, double price)
	{
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public Student()
	{
		super();
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public double getPrice()
	{
		return price;
	}

	public void setPrice(double price)
	{
		this.price = price;
	}

	@Override
	public String toString()
	{
		return "Student [id=" + id + ", name=" + name + ", price=" + price+ "]";
	}
}

package com.example.service;
import com.example.service.Student;
interface IStudentService 
{
	Student getStudentById(int id);
}

package com.example.service;
parcelable Student;
对应下面四个文件

在这里插入图片描述

客户端
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="bindRemoteService"
        android:text="bind remote Service" />

    <EditText
        android:id="@+id/et_aidl_id"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:hint="学员ID"
        android:text="3" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="invokeRemote"
        android:text="调用远程服务端的方法" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="unbindRemoteService"
        android:text="unbind remote Service" />

</LinearLayout>

package com.example.client;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.service.IStudentService;
import com.example.service.Student;

public class MainActivity extends Activity
{
	private EditText et_aidl_id;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		et_aidl_id = (EditText) findViewById(R.id.et_aidl_id);
	}

	private ServiceConnection conn;
	private IStudentService studentService;

	public void bindRemoteService(View v)
	{

		Intent intent = new Intent("com.example.service.MyRemoteService.Action");
		if (conn == null)
		{
			conn = new ServiceConnection()
			{
				@Override
				public void onServiceDisconnected(ComponentName name)
				{

				}

				@Override
				public void onServiceConnected(ComponentName name,IBinder service)
				{
					Log.e("TAG", "onServiceConnected()");
					studentService = IStudentService.Stub.asInterface(service);
				}
			};
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
			Toast.makeText(this, "绑定Service", 0).show();
		} else
		{
			Toast.makeText(this, "已经绑定Service", 0).show();
		}
	}

	public void invokeRemote(View v) throws RemoteException
	{
		if (studentService != null)
		{
			int id = Integer.parseInt(et_aidl_id.getText().toString());
			Student student = studentService.getStudentById(id);
			Toast.makeText(this, student.toString(), 0).show();
		}
	}

	public void unbindRemoteService(View v)
	{
		if (conn != null)
		{
			unbindService(conn);
			conn = null;
			studentService = null;
			Toast.makeText(this, "解绑Service", 0).show();
		} else
		{
			Toast.makeText(this, "还未绑定Service", 0).show();
		}
	}
}

还需要导入服务端AIDL的相关定义
比如
	Student.java
	IStudentService.aidl
	Student.aidl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReflectMirroring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值