In Android development, service as a 4 component is often used in development. Most of the time, our activity and service need to interact with each other, the activity needs to invoke the method inside the service to implement some functions, service needs to invoke the activity of the method, to implement interface updates and other interactions.
the main ways to achieve interaction between the 2 are: the service has a class section that inherits the binder, and then provides a public method that returns an instance of the current service. Activity through Bindservice to open a Service,service by Onbind method, return a IBinder instance (the class instance that we created), Activity through the Onserviceconnected method, get the IBinder instance, and then through the IBinder instance to get the service instance, so we get the service instance, Then our activity can use its various methods to manipulate it at will.
The activity above can operate the service, and we also need the service to operate the activity.
I think there can be 3 ways:
1. Transfer the activity directly to service,service and manipulate the activity with an activity instance.
2. Use the interface callback method, the activity implements the corresponding interface, service through the interface callback, more flexible
3. Use the Broadcast
The use of radio is a more common way, we do not specifically explain, the following we introduce the previous 2 methods, specific look at the code, with Service update Seekbar.
Our Activity code:
Package Com.hck.bindservice;import Android.app.activity;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.util.log;import Android.view.view;import Android.widget.seekbar;import Android.widget.toast;import Com.hck.bindservice.myservice.mybuild;public class Mainactivity extends Activity { Private MyService MyService; Our own service private SeekBar PBar; Simulation Service update progress bar private connectionservice connectionservice; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main);p bar = (SeekBar) Findviewbyid (R.id.seekbar); connectionservice=new Connectionservice (); }public void StartService (view view) {//Bind service Bindservice (new Intent (This,myservice.class), Connectionservice, 1);} /** * * @author Administrator * Implements the service interface for service bindings, callback */class Connectionservice implements Serviceconnection{@Overridepublic void onserviceconnected (componentname name, IBinder service) {myservice= ((mybuild) service). Getmyservice (); Gets the MyService object/** * Directly passes the current object to service so that the service can invoke the various available methods of the activity */myservice.setmainactivity ( Mainactivity.this); Passing the current object to myservice/** * uses an interface to implement callbacks, which is more flexible than the above method, and recommends *///myservice.setonprogressbarlistener (new Updateprogresslistener () {////@Override//public void updatebar (int size) {//updatebar (size);//}//});} @Overridepublic void onservicedisconnected (componentname name) {}}/** * * @param size * update seekbar */public void Updatebar (int size) {pbar.setprogress (size);} /** * * @param view * Start updating Seekbar */public void Startbar (view view) {if (myservice==null) {Toast.maketext (this, "first Start Service ", Toast.length_long). Show (); } else {myservice.startupdateprogress ();}} /** * * @param view * Stop updating Seekbar */public void Stopbar (view view) {if (myservice==null) {Toast.maketext (this, "Update does not start", Toast.length_long). Show (); } else {Myservice.stopupdateprogreSS ();}} /** * * @param view * Stop service */public void StopService (view view) {Myservice=null;unbindservice (connectionservice);} @Overrideprotected void OnDestroy () {Super.ondestroy (); try {unbindservice (connectionservice);} catch (Exception e) {}} }
The important code is the onserviceconnected callback method inside
Myservice= ((mybuild) service). Getmyservice (); Get MyService Object
After getting the service object, we want to do it all the way, such as above, the activity instance directly through its method passed, easy to
Service invokes the various methods of activity. Or, set pass a callback interface object past, user callback
Service Code:
Package Com.hck.bindservice;import Android.app.service;import Android.content.intent;import android.os.Binder; Import Android.os.handler;import Android.os.ibinder;import Android.util.log;public class MyService extends Service{ private int size=0; Private UpdateProgress UpdateProgress; Private final long time=2000; Private Boolean isupdate=true; Private mainactivity activity; Private Updateprogresslistener listener; @Overridepublic ibinder onbind (Intent Intent) {return new Mybuild ();} @Overridepublic void OnCreate () {super.oncreate (); updateprogress=new updateprogress ();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {return Super.onstartcommand (Intent, Flags, STA Rtid);} /** * * @author Administrator * thread used to change the size of seekbar progress * */class UpdateProgress implements runnable{@Overridepublic void Run ( {if (isupdate) {size+=10; if (size>100) {size=0;} Handler.sendemptymessage (0);}} /** * Call Update appropriate method, update progress bar */handler handler=new Handler () {PUBlic void Handlemessage (Android.os.Message msg) {/** * directly invokes the method inside the Activity object */if (activity!=null) {Activity.updatebar ( size);} /** * Use interface callback *///if (listener!=null) {//listener.updatebar (size);//}handler.postdelayed (updateprogress, time);};};/ * * Stop updating */public void Stopupdateprogress () {isupdate=false;} /** * Open update */public void startupdateprogress () {if (!isupdate) {handler.post (updateprogress);} Isupdate=true;} public void OnDestroy () {isupdate=false;};/ * * * @param activity * Initialize mainactivity object */public void Setmainactivity (mainactivity activity) {this.activity=activity;} /** * * @param listener * Initialize Updateprogresslistener object */public void Setonprogressbarlistener (Updateprogresslistener list Ener) {This.listener=listener;} /** * * @author Administrator * Use class classes to return instances of the current service for activity, various methods of invoking service * */class Mybuild extends Binder{public My Service Getmyservice () {return myservice.this;}}}
The most important thing in the service is, the bottom of our Mybuild class, through its Getmyservice method, get the instance of service
Instances of this class are really onbind when we return to the activity.
Interface:
Package Com.hck.bindservice;public interface Updateprogresslistener {public void Updatebar (int size);}
A simple interface for service callback activity
The above is the use of Bindservice to start the service, then if we use StartService start service, the above method is not.
Because Onbind does not execute, we do not get the IBinder instance. At this point, we can use the observer pattern of the design pattern to handle it.
Other not clear, there is nothing better than the way, I did not think, have to know the friend, please inform, thank you
Example Source: http://download.csdn.net/detail/hhhccckkk/8469069
Please isupdate=true the private boolean; Change to private Boolean isupdate=false;
Interactive Introduction to Android activity and service