2.创建完毕后,刷新一下,可以在R.gen下面看到代理实现的Iperson.java文件
3.实现aidl接口,如IpersonImpl.java就是实现IPerson.aidl中的接口
4.使用Service将接口暴露给客户端调用。如下面的MyRemoteService.java
5.客户端调用这个接口,即可。
后记:后面会在两个应用程序之间进行数据调用。
package com.king.android.controls;
//IPerson接口
interface IPerson{
//设置年龄
void setAge(int age);
//设置姓名
void setName(String name);
//信息展示
String display();
}
package com.king.android.controls;
import android.os.RemoteException;
/**
* 描述:实现Iperson.aidl接口
* 作者:Andy.Liu
* 时间: 2012-7-18 下午10:44:27
**/
public class IPersonImpl extends IPerson.Stub {
private int age;
private String name;
@Override
public String display() throws RemoteException {
return "name:"+name+";age="+age;
}
@Override
public void setAge(int age) throws RemoteException {
this.age = age;
}
@Override
public void setName(String name) throws RemoteException {
this.name = name;
}
}
package com.king.android.controls;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.king.android.controls.IPerson.Stub;
/**
* 描述:使用service将接口暴露给客户端
* 作者:Andy.Liu
* 时间: 2012-7-18 下午10:47:47
**/
public class MyRemoteService extends Service {
//声明Iperson接口
private Stub iPerson = new IPersonImpl();
@Override
public IBinder onBind(Intent intent) {
return iPerson;
}
}
package com.king.android.controls;
import com.king.android.R;
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.Toast;
/**
* 描述:测试Aidl
* 作者:Andy.Liu
* 时间: 2012-7-18 下午10:54:00
**/
public class MainActivity extends Activity {
private static final String MY_SERVICE = "com.king.android.controls.MY_REMOTE_SERVICE";//服务指定的动作
//声明IPerson接口
private IPerson iPerson;
private Button btn;
//实例化Serviceconnection
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn_voice);
btn.setVisibility(View.VISIBLE);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(MY_SERVICE);
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
}
private ServiceConnection conn = new ServiceConnection() {
@Override
synchronized public void onServiceConnected(ComponentName name, IBinder service) {
iPerson = IPerson.Stub.asInterface(service);
if(null!=iPerson){
//RPC调用方法
try {
iPerson.setName("king.android.iphone");
iPerson.setAge(30);
String msg = iPerson.display();
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}