Why introduce Bindservice: purpose in order to invoke the method inside the service
(1) Define a service service there is a method that requires activity calls
(2) Define an intermediary object (IBinder) to inherit binder
(3) in the Onbind method, we return the intermediary object we define.
(4) in the OnCreate method of activity, the purpose of calling Bindservice is to get the intermediary object we define.
(4.1) Get the Middleman object
(5) When you get the intermediary object, you can indirectly call the method inside the service.
Public classTestserviceextendsService {//when Bindservice@Override Publicibinder onbind (Intent Intent) {//[3] returning the man-in-the-middle object we define return NewMybinder (); } @Override Public voidonCreate () {Super. OnCreate (); } //test Method Public voidBanzheng (intMoney ) { if(Money > 1000) {Toast.maketext (Getapplicationcontext (),"I am the leader to give you the card," 1). Show (); }Else{Toast.maketext (Getapplicationcontext (),"This money still wants to work", 1). Show (); } } //[1 Defining an intermediary object] Public classMybinderextendsbinder{//[2] defining a method to invoke the certificate method Public voidCallbanzheng (intMoney ) {Banzheng (money); } } }
Public classMainactivityextendsActivity {PrivateMybinder Mybinder;//This is a man-in-the-middle object we define@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); // //Open ServiceIntent Intent =NewIntent ( This, Testservice.class); //Connection Service TestserviceMyConn conn =Newmyconn (); //Binding ServiceBindservice (Intent, Conn, bind_auto_create); } //Click the button to invoke the Testservice service inside the certificate method Public voidClick (View v) {//indirectly invoking the method inside the service through our defined intermediary objectMybinder.callbanzheng (102); } //monitoring the status of a service Private classMyConnImplementsserviceconnection{//When the connection service succeeds@Override Public voidonserviceconnected (componentname name, IBinder service) {//[4] Get our defined man-in-the-middle objectMybinder=(mybinder) service; } //Lost connection@Override Public voidonservicedisconnected (componentname name) {} }}
To invoke the procedure inside a service method by means of Bindservice