This two-day review of Android service knowledge, before the memory fades, to summarize. This article mainly explains the basic concept and use of service, the use of cross-process call service, System common service. So this article is very difficult, only for the students who want to review the service knowledge points, or do not know the service of the classmate, as to the service source and other things, such as the analysis of the past, and then to share.
First, service base
I believe that as long as people who have contact with Android developers, have more or less know the service. What is the service? The service is the most similar component in Android's four components, it has its own life cycle, but it does not have the same gorgeous appearance as activity, it silently pay in the background all the year round. The service is also an executable program, which says it has its own life cycle, which is created in a configuration process that is very similar to activity. Furthermore, activity and service have a common father context, so they can all invoke methods defined in the context such as getresources (), Getcontentresolver (), and so on.
1, the service simple use:
Developing a service requires two steps: (1) defines a subclass that inherits the service. (2) Configure the service in the Androidmanifest.xml file.
Before you start developing your first service, let's take a look at the service's family lifecycle approach:
(1) IBinder onbind (Intent Intent): This method is a method that the service subclass must implement. The method returns an IBinder object that the application can use to communicate with the service component.
(2) void OnCreate (): The method is immediately called back when the service is created for the first time.
(3) void OnDestroy (): The method will be recalled before the service is closed.
(4) void Onstartcommand (Intent intent,int flags,int Startid): Earlier versions of the method were void OnStart (Intent intent,int Startid), The method is called back each time the client calls the StartService (Intent) method to start the service.
(5) Boolean onunbind (Intent Intent): This method will be recalled when all clients bound by the service are disconnected.
Let's develop our first service with the following code:
Package Com.gc.servicetest;import Android.app.notification;import Android.app.pendingintent;import Android.app.service;import Android.content.intent;import Android.os.binder;import Android.os.IBinder;import android.util.log;/** * Note: the OnCreate () method is only called when the service is created for the first time, if the current service has been created, * anyway, call the StartService method, OnCreate () method is no longer executed. * @author Android General * */public class MyService extends service{public static final String Tag=myservice.class.getsimplenam E ();//The method that must be implemented @overridepublic IBinder Onbind (Intent Intent) {//TODO auto-generated method STUBLOG.V (TAG, "Onbind () Executed "); return null;} The service was created when the callback method @overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); LOG.V (TAG, "onCreate () executed"); LOG.V (TAG, "MyService thread ID is" +thread.currentthread (). GetId ()); }//service is started when callback this method @overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generate D Method STUBLOG.V (TAG, "Onstartcommand () executed"); return suPer.onstartcommand (Intent, flags, Startid);} The service is closed before the callback method @overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); LOG.V (TAG, "OnDestroy () executed");}}
The service above does nothing-it simply rewrites the service component's OnCreate (), Onstartcommand (), OnDestroy (), Onbind (), and so on. If you want the service component to do something, just define the relevant business code in the OnCreate () or Onstartcommand () method. Two steps to develop the service, we have now finished the first step, let's take the second step together. The second step is simple, configuring the service in Androidmanifest.xml is the same as configuring the activity in the file, except that the label is <service.../> one is <activity .../>. Here is the configuration for this myservice, the code is as follows:
<service android:name= ". MyService "></service>
When the two steps are completed, we have developed a service component that will then run the service in the program, and there are two ways to run the service on the Android system, as follows:
(1) Through the context of the StartService () method: Start the service through this method, the visitor is not associated with the service, even if the visitor exits, the service is still running.
(2) Through the context of the Bindservice () method: Use this method to enable the service, the visitor is bound together with the service, and once the visitor exits, the service terminates.
Let's look at how to use these two methods to launch the MyService we just developed, we use activity as a service visitor, the activity interface contains four buttons, because the code is simple, here no longer give its layout file, Here's a look at the mainactivity code, as follows
Package Com.gc.servicetest;import Com.gc.servicetest.myservice.mybinder;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.menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import android.widget.button;/** * * @author Android General * */public Class Mainactivity extends Activity implements Onclicklistener {public static final String tag=mainactivity.class.getsimplename (); Private Button Mbtnstartservice; Private Button Mbtnstopservice; Private Button Mbtnbindservice; Private Button Mbtnunbindservice; Private Myservice.mybinder Mybinder; Private serviceconnection connection=new serviceconnection () {@Overridepublic void onservicedisconnected ( ComponentName name) {//TODO auto-generated method STUBLOG.V (TAG, "onservicedisconnected () executed"); LOG.V (TAG, "onservicedisconnected () executed name" +name); @Overridepublic void onserviceconnected (componentname name, IBinder service) {//TODO auto-generated method STUBLOG.V ( TAG, "onserviceconnected () executed"); LOG.V (TAG, "onserviceconnected () executed name" +name); mybinder= (Mybinder) service;mybinder.startdownload ();}; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initui (); Setlistener (); LOG.V (TAG, "Mainactivity thread ID is" +thread.currentthread (). GetId ()); }public void Initui () {mbtnstartservice= (button) Findviewbyid (R.id.start_service); mbtnstopservice= (Button) Findviewbyid (R.id.stop_service); mbtnbindservice= (Button) Findviewbyid (R.id.bind_service); Mbtnunbindservice= ( Button) Findviewbyid (r.id.unbind_service);} public void Setlistener () {Mbtnstartservice.setonclicklistener (this), Mbtnstopservice.setonclicklistener (this); Mbtnbindservice.setonclicklistEner (this); Mbtnunbindservice.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.id.start_service:inten T mstartintent=new Intent (this, myservice.class); StartService (mstartintent); Break;case r.id.stop_service:intent Mstopintent=new Intent (this, myservice.class); StopService (mstopintent); Break;case r.id.bind_service:intent Mbindintent=new Intent (this, myservice.class); Bindservice (mbindintent, Connection, bind_auto_create); break;case R.id.unbind_service:unbindservice (connection); break;default:break;}}
So far, we've written a program with a service feature. Then we run the program, click the Start Service button, and then click the Stop Service button to see the following print results:
If you do not close the service, click the Start Sevice button three times, the program will start the service three times in a row, printing information as follows:
From the above two different operation and printing information, we have verified the correctness of the contents of the previous MyService note section, as follows:
The OnCreate () method is only called when the service is created for the first time, and if the current service has been created, the OnCreate () method will no longer execute if the StartService method is invoked anyway.
Now that we've learned the first way, then I'll take a look at the second way:
In the first way, there is essentially no association between MyService and Mainactivity, so communication and data exchange between MyService and mainactivity is not possible. If you want to make a method call or data exchange between MyService and Mainactivity, you should start the MyService in the second way, using the Bindservice () and Unbindservice () methods to start and close the service. Before starting MyService in the second way, it is definitely to modify the previous MyService code, the following code is modified:
public class MyService extends service{public static final String tag=myservice.class.getsimplename ();p rivate mybinder mbinder=new Mybinder (); @Overridepublic ibinder Onbind (Intent Intent) {//TODO auto-generated method STUBLOG.V (TAG, "Onbind () Executed "); return mbinder;} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); LOG.V (TAG, "onCreate () executed"); LOG.V (TAG, "MyService thread ID is" +thread.currentthread (). GetId ()); } @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method STUBLOG.V (TAG, " Onstartcommand () executed "); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); LOG.V (TAG, "OnDestroy () executed");} Class Mybinder extends Binder{public void Startdownload () {LOG.V (TAG, "startdownload () executed");}}
Before we proceed, let's look at the Bindservice method:
The source code for the Bindservice () method in the context is as follows:
public boolean bindservice (Intent service, serviceconnection conn, int flags) { return Mbase.bindservice ( SERVICE, Conn, flags); }
Here is an explanation of the three parameters of the method:
Service: This parameter specifies the service to start with intent.
Conn: This parameter is an Serviceconnection object that listens to the connection between the visitor and the service. The onserviceconnected (componentname Name,ibinder Service) method of the Serviceconnecttion object will be recalled when the connection between the visitor and the service succeeds The Serviceconnection object's onservicedisconnected is recalled when the service's host process terminates due to an unexpected termination or other reason, causing the service to disconnect from the visitor ( ComponentName name) method.
Note: When the caller actively disconnects from the service through the Unbindservice () method, the Serviceconnection object's onservicedisconnected (componentname name) method is not called.
Flags: Specifies whether the service is automatically created when binding (if the service has not yet been created). This parameter can be specified as 0 (not created automatically) or bind_auto_create (automatically created).
Notice that the onserviceconnected method of the Serviceconnection object has a IBinder object that can communicate with the service being bound.
Well, long-winded so much, is not a bit dizzy, let's see the second way to start myservice execution effect bar, run the program, click on the Bind service, and then click Unbind Service, print information as follows:
As we can see, Mainactivity has successfully communicated with MyService. We called the Startdownload () method in the Onserviceconnected method of the member object connection of Mainactivity.
Let's summarize here:
Developing a service requires two steps: (1) defines a subclass that inherits the service. (2) Configure the service in the Androidmanifest.xml file.
There are two ways to start a service: (1) StartService method (2) Bindservice method
Starting Service,service by StartService is basically not much of an association with visitors. The service is initiated by Bindservice to enable communication between the service and the visitor. So how do you communicate when you start a service through Bindservice? As we have analysed in this case, when we develop the MyService class, we must implement the method IBinder Onbinder (Intent Intent), when we start bindservice through the MyService method, We've bound mainactivity with MyService, The IBinder object returned by the Onbind method of the MyService method is then passed to the connection of the Mainactivity member onserviceconnected (componentname Name,ibinder Service) method, so that mainactivity can communicate with MyService through the IBinder object.
Careful communication will find that the Onstartcommand method was called when the service was started by StartService, and the Onstartcommand method was not called when the service was started by the Bindservice method. This is because the service is started in two ways, resulting in a slightly different life cycle for the service. In the next service life cycle, I will tell you clearly.
OK, BB has so much, I think the basic knowledge of the service should be almost, I will provide the demo at the end of the article, if you have help can be a little to the top of the Austrian, if there is incorrect in the text, welcome to point out, if there are questions, or I did not clarify the place, please leave a message, Thank you.
Reprint Please specify source: http://blog.csdn.net/android_jiangjun/article/details/45458063
Android Review Service's service base usage