Android featured 8--Local Service and remote service communication

Source: Internet
Author: User

About Remote Services
    • A remote service refers to a service and a visitor that are not in the same application, that is, not in the same process.
    • Access to remote services is similar to interprocess communication.
    • Visitors and remote services need to comply with protocols that can be understood by the operating system, aidl.
1. On the server side and the client configuration Aidl
    • Aidl files are best placed in the Aidl directory, aidl files are used for interface descriptions
    • A Java file with the same name will be generated automatically
    • In the automatically generated Java file, a stub class is automatically defined, inheriting the Binder class, implementing the interface described in the Aidl file

2. Writing Service business code
    • Registering in the manifest file
    • Implementing a custom IBinder
        <service android:name=". Studentservice">            <intent-filter >                <action android:name="  Com.njulya.REMOTESERVICE"/>            </intent-filter>        </service>
View Code
ImportCom.njulya.aidl.StudentQuery;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder;Importandroid.os.RemoteException; Public classStudentserviceextendsService {IBinder ibinder; String[] Names= {"Zhang Yang", "Mr. Li Yongan", "Jay"}; @Override Publicibinder onbind (Intent Intent) {IBinder=NewStudentbinder (); returnIBinder; }/*** Implementation of IBinder interface for communication *@authorAndy*/    Private classStudentbinderextendsstudentquery.stub{@Override//interfaces described in the Aidl file         PublicString Query (intNothrowsRemoteException {returnNAMES[NO-1];//Business code        }            }}
View Code

3. Writing client applications
 Packagecom.njulya.remoteserviceclient;ImportCom.njulya.aidl.StudentQuery;Importandroid.app.Activity;ImportAndroid.content.ComponentName;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateEditText StudentID; PrivateTextView content; PrivateStudentquery Studentquery; PrivateServiceconnection Conn; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); StudentID= (EditText) This. Findviewbyid (r.id.student_id); Content= (TextView) This. Findviewbyid (r.id.content); Conn=Newstudentconnetion (); Intent Service=NewIntent ("Com.njulya.REMOTESERVICE");  This. Bindservice (Service, Conn, bind_auto_create); }    /*** Key to trigger business code *@paramv*/     Public voidQueryonclick (View v) {intNo =integer.valueof (Studentid.gettext (). toString ()); Try{String Studentname=studentquery.query (NO);        Content.settext (Studentname); } Catch(RemoteException e) {e.printstacktrace (); }    }    Private classStudentconnetionImplementsserviceconnection{@Override Public voidonserviceconnected (componentname name, IBinder service) {//To convert a IBinder proxy object to an interface typeStudentquery =StudentQuery.Stub.asInterface (service); } @Override Public voidonservicedisconnected (componentname name) {studentquery=NULL; }} @Overrideprotected voidOnDestroy () {unbindservice (conn); Super. OnDestroy (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }    }
View Code

About local services
    • The service started is running in the main thread, so the time-consuming operation is to create a new worker thread
    • When using Bindservice, it is necessary to implement Serviceconnection,flags Bind_auto_create
    • The key to the service is to return the implementation class object for IBinder, which uses some of the APIs in the service
    • Typically get and close IBinder objects in a custom Serviceconnection implementation class
    • Invoking the API in the service through the resulting IBinder object implementation
Business interface

Client code
 Packagecom.njulya.intsum;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;Importandroid.app.Activity;ImportAndroid.content.ComponentName;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateEditText NUM1; PrivateEditText num2; PrivateTextView sum; PrivateServiceconnection Conn; //custom public interface for the sum of two numbers    PrivateSumoftwo Sumoftwo; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); NUM1= (EditText) This. Findviewbyid (R.ID.NUM1); Num2= (EditText) This. Findviewbyid (R.ID.NUM2); Sum= (TextView) This. Findviewbyid (R.id.sum); Button Button= (Button) This. Findviewbyid (R.id.button); Button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {sum ();        }        }); Conn=Newsumconnetion (); Intent Service=NewIntent ( This, Sumservice.class);  This. Bindservice (Service, Conn, bind_auto_create); }    protected voidsum () {intNumber1 =integer.valueof (Num1.gettext (). toString ()); intNumber2 =integer.valueof (Num2.gettext (). toString ()); intresult =sumoftwo.sum (Number1, number2);            Sum.settext (string.valueof (result)); }    Private classSumconnetionImplementsserviceconnection{@Override Public voidonserviceconnected (componentname name, IBinder service) {Sumoftwo=(sumoftwo) service; } @Override Public voidonservicedisconnected (componentname name) {Sumoftwo=NULL; }} @Overrideprotected voidOnDestroy () {unbindservice (conn); Super. OnDestroy (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }}
View CodeService-side code
 Packagecom.njulya.intsum;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder; Public classSumserviceextendsService {@Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        return NewSumbinder (); }     Public classSumbinderextendsBinderImplementssumoftwo{@Override Public intSumintNumber1,intnumber2) {            returnNumber1 +number2; }            }}
View Code

Android featured 8--Local Service and remote service communication

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.