PackageCom.example.administrator.test.Fragment.Service;ImportAndroid.app.IntentService;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.net.Uri;ImportAndroid.os.IBinder;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Toast;ImportCOM.EXAMPLE.ADMINISTRATOR.TEST.R;Importcom.google.android.gms.appindexing.Action;ImportCom.google.android.gms.appindexing.AppIndex;Importcom.google.android.gms.appindexing.Thing;Importcom.google.android.gms.common.api.GoogleApiClient; Public classTestserviceextendsappcompatactivity { Public voidBt1_onclick (View v) {Intent Intent=NewIntent ( This, MyService.class ); Intent.putextra ("Test", "Sent data" ); StartService (Intent); Toast.maketext ( This, "MyService is started", Toast.length_short). Show (); } Public voidBt2_onclick (View v) {Intent Intent=NewIntent ( This, MyService.class ); StopService (Intent); Toast.maketext ( This, "MyService has stopped", Toast.length_short). Show (); } serviceconnection SC; Myservice.mybinder Myb; //Binding Method Public voidBt3_onclick (View v) {Intent Intent=NewIntent ( This, MyService.class ); if(sc = =NULL) SC =Newserviceconnection () {@Override Public voidonserviceconnected (componentname componentname, IBinder ibinder) {//Receive proxy objectsMyb =(Myservice.mybinder) IBinder; Toast.maketext (Testservice. This, "The binding starts to complete, receives the returned object, reads the data =" +myb.gettest (), Toast.length_short). Show (); } @Override Public voidonservicedisconnected (componentname componentname) {toast.maketext (testservice. This, "Service Connection Disconnected", Toast.length_short). Show (); } }; //three parameters: 1. Intent 2. Service Connection 3. Starting modeBindservice (Intent, SC, context.bind_auto_create);//automatically created } //Unbind Public voidBt4_onclick (View v) {if(sc!=NULL) {Unbindservice (SC); SC=NULL; }Else{Toast.maketext ( This, "Bind service First", Toast.length_short). Show (); } }}
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" > <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Normal mode start"Android:onclick= "Bt1_onclick"/> <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Normal mode stop"Android:onclick= "Bt2_onclick"/> <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "bind mode start"Android:onclick= "Bt3_onclick"/> <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Unbind mode Stop"Android:onclick= "Bt4_onclick"/></LinearLayout>
Wangzai exercises: The normal way of service and the start and stop of binding mode