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();
}
}
}
}