"Turn" Pro Android Learning Note (80): Service (5): Access remote Service

Source: Internet
Author: User

Directory (?) [-]

    1. Client's Aidl file
    2. Client's Code
      1. Establish a connection
      2. Request Service
      3. Disconnect Connection

The articles reproduced can only be used for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other additional conditions. Reprint must indicate the source: http://blog.csdn.net/flowingflying/

Unlike the local service, remote service can be called by other processes, that is, other applications.

The client's Aidl file returns the stub object to the Client,client operation on the stub object in Onbind (), as if it were an external interface to the service. Following the implementation of the Aidl file and the remote service, we will learn how the client accesses the remote service.

Client's Aidl file

To access the remote service, the client must be aware of the service interface, so it is also necessary to use the Aidl file to describe the interface, which can be copied directly from the remote service, and the Aidl file is the contract between the client and the server, which describes the interface between the two parties.

We copy the Istockquoteservice.aidl file from the remote service to the client's SRC. Since the package name in Aidl is not the same as the package name of the client, we will see the following view:

Client's Code

The client's activity is very simple, the main two buttons, the first one is ToggleButton, there are two states, click to connect the remote service and disconnected, that is, bind and unbind. The second button is to request a remote service, and the resulting results are displayed with a toast, and the service can only be requested after a successful connection to the remote service, so the button depends on whether the connection state does enable.

public class Mainactivity extends Activity {
Private ToggleButton Bindbutton = null;
Private Button Callbutton = null;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Bindbutton = (ToggleButton) Findviewbyid (R.id.bindbutton);
Callbutton = (Button) Findviewbyid (R.id.callbutton);
}

@Override
protected void OnDestroy () {
LOG.V ("Client", "Activity OnDestroy () is called");
if (bindbutton.ischecked ()) {
Unbindservice (Servcon);//"3" disconnects when activity exits
}
Super.ondestroy ();
}

Press button for processing
public void DoClick (View v) {
Switch (V.getid ()) {
Case R.id.bindbutton:
LOG.V ("Client", "Bindbutton check?") "+ bindbutton.ischecked ());
if (bindbutton.ischecked ()) {//want bind
/*"1" Connection remote service: Through Bindservice (), there are three parameters:
* 1, the name of the service, we defined in the androidmanifest.xml of the remote service in <intent-fliter>
* 2, Serviceconnetion, connection
* 3, flag, indicates that the service is created automatically if it exists.
* */
Bindservice (New Intent (IStockQuoteService.class.getName ()),
Servcon,
Context.bind_auto_create);

}else{//want Unbind
Callbutton.setenabled (FALSE);
Unbindservice (Servcon); "3" Disconnect service
}
Break

Case R.id.callbutton:
Callservice ();
Break

Default
Return
}
}
//"1" Connect remote service
Private Istockquoteservice remoteservice = null;
//"1.1" stores proxy instances in stubs returned by remote services
private Serviceconnection Servcon = new Serviceconnection () {
@Override//"1.2" occurs when a remote service has an exception, such as crash, which causes the connection to break, note that Unbindservice () does not trigger this.
Public void onservicedisconnected (componentname name) {
LOG.V ("Client", "onservicedisconnected () is called");
Bindbutton.setchecked (FALSE);
Callbutton.setenabled (FALSE);
Remoteservice = null;
}

@Override//"1.3" When the remote service connection succeeds, that is, the bindservice () trigger when successful, it is necessary to obtain the stub object, actually obtains the proxy instance in the stub, operates this proxy object, just like the direct Operation remote service, the use is very convenient.
Public void onserviceconnected (componentname name, IBinder service){
LOG.V ("Client", "onserviceconnected () is called");
To get a proxy object from an interface, manipulate the object as if it were a generic interface, the following is the code in the auto-generated interface file.
/*in Istockquoteservice.stub: Gets a IBinder object in the interface as a proxy (proxy), there is a return, none is generated.
* Cast an IBinder object to an Cn.wei.flowingflying.proandroidservice.IStockQuoteService interface,
* Generating a proxy if needed.
* public static Cn.wei.flowingflying.proandroidservice.IStockQuoteServiceAsinterface(Android.os.IBinder obj)
{
if ((Obj==null)) {
return null;
}
Android.os.IInterface iin = obj.querylocalinterface (descriptor);
if (((iin!=null) && (iin instanceof Cn.wei.flowingflying.proandroidservice.IStockQuoteService)) {
Return ((Cn.wei.flowingflying.proandroidservice.IStockQuoteService) iin);
}
return new Cn.wei.flowingflying.proandroidservice.IStockQuoteService.Stub.Proxy (obj);
}
* */
Remoteservice = IStockQuoteService.Stub.asInterface (service);
Bindbutton.setchecked (TRUE);
Callbutton.setenabled (TRUE);
}
};

private void Callservice () {
try{
Double value = Remoteservice.getquote ("WEI"); "2" Request Service: Operation interface Proxy instance, if local Operation remote service interface
LOG.V ("Client", "Callservice (): Get StockQuote from Reference:" + value);
Toast.maketext (This, "Stock quote is" + value, Toast.length_long). Show ();
}catch (RemoteException e) {
LOG.E ("Client", e.tostring ());
}
}
}

Client access to the remote service is divided into three steps: "1" establishes the connection, "2" Request Service, "3" disconnects.

Establish a connection

Remote services can be called by the application and other applications, the client establishes a connection through Bindservice () and the remote service, and obtains an interface proxy object from it. The corresponding in the remote service, if the service does not exist, the service starts, executes OnCreate (), then executes Onbind (), and executes the onbind () directly if the service exists.

Bindservice () is asynchronous, that is, asynchronouse call, which means that it does not wait until the service finishes executing OnCreate (), Onbind (), and then returns, So we need the onserviceconnected () callback function in Serviceconnection to indicate that the connection was successful. The onservicedisconnected () in serviceconnection is triggered when the service crashes, and the Android system automatically restarts the service if there is a connection. We can do this by forcing the process of terminating the remote service in DDMS, we can see that onservicedisconnected () is triggered, the remote service is restarted, and then the connected onserviceconnected ( ) will be triggered.

Request Service

Direct operation of the interface proxy instance, the operation of remote services is as convenient as local operations.

Disconnect Connection

Disconnect the remote service via Unbindservice () and execute the remote service OnDestroy () accordingly. Maybe you'll worry if I do unbindservice () in the program, or it won't affect the other app's call to the remote service. There's no need to worry. In the last study, we traced a static variable (static int count) in the remote service. When we unbind the new bind, we find that count continues to count instead of starting over, stating that the service actually always exists in the background, which can also be determined by DDMS the view process. This is interesting, the stub is for each interface, and the OnCreate (), OnDestroy (), Onbind () in the remote service are also for the connection, or for the stubs allocated for each interface. So when different applications connect to remote services and request services or access services, there is no confusion between them, and the service can separate each connection. Of course, if we do not use static variables, and use ordinary variables, unbind after bind, will be new count.

This note covers example code that can be downloaded in the Pro Android Learning: Android Service Small example.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (80): Service (5): Access remote Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.