1. RPC service:
(1) Create an aidl file to define interfaces for the client
The aidl file uses the Java syntax. Its extension is the package name used by Dot. aidl, which is the same as the package used by the android project.
Package CN. gpb. Service;
Interface iperson {
Void setage (INT age );
Void setname (string name );
String display ();
}
(2) Add the aidl file to any package of the project. The android Eclipse plug-in calls the aidl compiler to generate a Java interface from the aidl file. In this step, the Eclipse plug-in ADT automatically generates code (under the package Gen ).
(3) implement a service and return the generated interface from the onbind () method.
/**
* Expose the interface to the client using the service
*/
Public class myremoteservice extends Service {
// Declare the iperson Interface
Private stub iperson = new ipersonimpl ();
@ Override
Public ibinder onbind (intent ){
Return iperson;
}
}
(4) Write implementation class ipersonimpl extends iperson. stub to implement the interface
/**
* Iperson implementation class
*/
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) Add the service configuration to the androidmanifest. xml file.
<! -- RPC service -->
<Service android: Name = ". Service. myremoteservice">
<Intent-filter>
<Action Android: Name = "cn. gpb. Service. myremote_service"/>
</Intent-filter>
</Service>
(5) Client connection:
Public class serviceactivity extends activity {
Private button rpcbutton;
Private iperson;
@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Service );
// Instantiate the button component
Rpcbutton = (button) findviewbyid (R. Id. rpcbutton); // RPC listener
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 ");
// Bind the service
Bindservice (intent, rpcconn, Service. bind_auto_create );
}
};
// RPC instantiate serviceconnection
Private serviceconnection rpcconn = new serviceconnection (){
Synchronized public void onserviceconnected (componentname, ibinder Service ){
// Obtain the iperson Interface
Iperson = iperson. stub. asinterface (service );
If (iperson! = NULL ){
Try {
Iperson. setname ("gongpeibao ");
Iperson. setage (25 );
String MSG = iperson. Display ();
// Display the return value of a method call
Toast. maketext (serviceactivity. This, MSG, Toast. length_long). Show ();
} Catch (RemoteException e ){
E. printstacktrace ();
}
}
}
}