1、RPC Service:
(1)创建一个AIDL文件来向客户端定义接口
AIDL 文件使用 java语法,它的扩展名是点 .aidl 使用的包名称与Android项目所使用的包相同
package cn.gpb.service;
interface IPerson{
void setAge(int age);
void setName(String name);
String display();
}
(2)将AIDL 文件添加到项目的任意包下。Android Eclipse 插件将调用AIDL编译器来从 AIDL 文件生成 Java接口。这一步是eclipse插件ADT自动生成代码(在包gen下面)。
(3)实现一个服务并从 onBind()方法返回所生成的接口。
/**
* 使用service将接口暴露给客户端
*/
public class MyRemoteService extends Service {
//声明IPerson接口
private Stub iperson = new IPersonImpl();
@Override
public IBinder onBind(Intent intent) {
return iperson;
}
}
(4)写实现类IPersonImpl extends IPerson.Stub 来实现接口
/**
* IPerson 的实现类
*/
public class IPersonImpl extends IPerson.Stub{
private int age;
private String name;
public String display() throws RemoteException {
return "name:"+name+" age: "+age;
}
public void setAge(int age) throws RemoteException {
this.age = age;
}
public void setName(String name) throws RemoteException {
this.name = name;
}
}
(4)将服务配置添加到 AndroidManifest.xml文件中 。
<!-- RPC Service-->
<service android:name=".service.MyRemoteService" >
<intent-filter >
<action android:name="cn.gpb.service.MyRemote_service" />
</intent-filter>
</service>
(5)客户端进行连接:
public class ServiceActivity extends Activity {
private Button rpcButton;
private IPerson iperson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service);
// 实例化按钮组件
rpcButton = (Button) findViewById(R.id.rpcButton);//rpc监听
rpcButton.setOnClickListener(rpc_listener);
}
private OnClickListener rpc_listener = new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setAction("cn.gpb.service.MyRemote_service");
// 绑定服务
bindService(intent, rpcConn, Service.BIND_AUTO_CREATE);
}
};
//RPC 实例化ServiceConnection
private ServiceConnection rpcConn = new ServiceConnection() {
synchronized public void onServiceConnected(ComponentName name, IBinder service) {
//获取IPerson接口
iperson = IPerson.Stub.asInterface(service);
if(iperson!=null){
try {
iperson.setName("gongpeibao");
iperson.setAge(25);
String msg = iperson.display();
//显示方法调用返回值
Toast.makeText(ServiceActivity.this, msg, Toast.LENGTH_LONG).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}