Aidl:android interface Define language (interface Definition language)
Function: Facilitates remote invocation of methods in other services
Note: All four components of Android must be registered in the manifest file
AIDL Create diagram:
Interface interfaceaidl { void interfacepay ();}
Public classMyServiceextendsService {classMybinderextendsinterfaceaidl.stub {@Override Public voidInterfacepay ()throwsremoteexception {pay (); }} @Nullable @Override Publicibinder onbind (Intent Intent) {Mybinder Binder=NewMybinder (); returnBinder; } Private voidPay () {LOG.I ("Service", "payment success"); }}
Public classMainactivityextendsappcompatactivity {PrivateIntent Intent; Privatemyserviceconnection myserviceconnection; PrivateInterfaceaidl Interfaceaidl; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intent=NewIntent ( This, MyService.class); Myserviceconnection=Newmyserviceconnection (); } Public voidbind (view view) {Bindservice (intent, myserviceconnection, bind_auto_create); } Public voidPay (view view) {Try{interfaceaidl.interfacepay (); } Catch(RemoteException e) {e.printstacktrace (); } } classMyserviceconnectionImplementsserviceconnection{@Override Public voidonserviceconnected (componentname name, IBinder service) {Interfaceaidl=InterfaceAidl.Stub.asInterface (service); } @Override Public voidonservicedisconnected (componentname name) {}} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Unbindservice (myserviceconnection); }}
Remote Call service
Interface interfaceaidl { void interfacepay ();}
<service android:name= ". MyService "> <intent-filter> <action android:name=" Aidl_interface.pay "></action> </intent-filter> </service>
Public classMainactivityextendsappcompatactivity {PrivateIntent Intent; PrivateInterfaceaidl Interfaceaidl; Privatemyserviceconnection myserviceconnection; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intent=NewIntent (); Myserviceconnection=Newmyserviceconnection (); Intent.setaction ("Aidl_interface.pay"); Intent.setpackage ("Com.example.administrator.aidlservice"); } Public voidbind (view view) {Bindservice (intent,myserviceconnection,bind_auto_create); } Public voidPay (view view) {Try{interfaceaidl.interfacepay (); } Catch(RemoteException e) {e.printstacktrace (); } } classMyserviceconnectionImplementsserviceconnection{@Override Public voidonserviceconnected (componentname name, IBinder service) {Interfaceaidl=InterfaceAidl.Stub.asInterface (service); } @Override Public voidonservicedisconnected (componentname name) {}} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Unbindservice (myserviceconnection); }}
Using Aidl to invoke methods in the service