Service as one of the four components of Android, it is not as high-profile as the activity (frequently used), it is the unknown worker.
Because it is not very useful, so the use of it is easy to forget, now have time to record it, convenient for later review.
Service is a solution that runs in the background of Android, and it is ideal for performing tasks that do not require interaction with the user and require long-term operation. The operation of the service does not depend on any user interface, even if the program is switched to the background, or if the user opens another application, the service remains operational.
It is important to note, however, that the service is not run in a separate process, but rather relies on the application process in which the service was created. When an application process is killed, all services that depend on the process also stop running.
In addition, do not be confused by the background concept of the service, in fact, the service does not automatically open the thread, all the code is run by default in the main thread. In other words, we need to manually create sub-threads within the service and perform specific tasks here, otherwise the main thread is likely to be blocked.
1. Create a service
Create a new service test class to inherit from service
public class MyService extends Service {@Overridepublic ibinder onbind (Intent Intent) {return null;}}
The Onbind () method is the only abstract method in the service, so it must be implemented in subclasses. It will be useful later on.
Create the service, presumably we will let it do some things, then the logic to deal with the code snippet placement where? This is where you need to rewrite some of the other methods in the service. The code snippet looks like this:
public class MyService extends Service {@Overridepublic ibinder onbind (Intent Intent) {return null;} @Overridepublic void OnCreate () {super.oncreate ();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {return Super.onstartcommand (Intent, Flags, STA Rtid);} @Overridepublic void OnDestroy () {Super.ondestroy ();}}
In the above code we rewrite the onCreate (), Onstartcommand (), OnDestroy ( ) methods, which are the three most common methods used in each service. where the OnCreate () method is called when the service is created, the Onstartcommand () method is invoked every time the service is started, and the OnDestroy () method is called when the service is destroyed. So what's the difference between the first 2 methods?
The OnCreate () method is called when the service is first created, and the Onstartcommand () method is called every time the service is started.
Normally, if we want the service to execute an action as soon as it is started, we can write the logic in the Onstartcommand () method. The code in the service is run by default in the main thread, and if you are dealing with time-consuming logic directly in the service, it is easy to get the application not responding. So when writing logic code in the Onstartcommand () method, it's a good idea to turn on a child thread to execute it in a child thread.
@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {new Thread (new Runnable () { @Override public void Run () { //process specific logic } }). Start (); return Super.onstartcommand (Intent, flags, Startid);}
And when the service is destroyed, we should reclaim those resources that are no longer used in the OnDestroy () method.
Note: Each service needs to be registered in the Androidmanifest.xml file in order to take effect, this is a common feature of Android four components, so we usually have to create a component is the habit of registering.
<service android:name= ". MyService "></service>
2. Start and stop services
Services start and stop in a similar way to activity, mainly through the use of intent.
Start the service in activity:
Intent startintent = new Intent (this, myservice.class); StartService (startintent); Start the service
To stop the service in activity:
Intent stopintent = new Intent (this, myservice.class); StopService (stopintent); Stop Service
Note: The above stop service is entirely up to the activity to determine when the service is stopped, and if there is no StopService () method above, the service will remain in the running state.
Is there any way for the service to stop itself? Of course, you just have to call the stopself () method at any point in the MyService to stop the service.
3. Communication of activities and services
Although the service is started in the activity, it seems that after StartService () in the activity, it becomes less easy to control our service, and we call the StartService () method in the activity to start the MyService service, Then MyService's OnCreate () and Onstartcommand () methods are executed. After that the service will always be running, but what logic is running, the activity will not be able to control, activities do not know what the service to do, and how to complete.
The abstract Method Onbind () mentioned earlier in this time can help us to make the activity and service closer together.
The following is an example of implementing a download function in MyService, which allows you to decide when to start the download and to see the progress of the download at any time.
To do this, we create a dedicated Binder object to manage the download function and modify the code in MyService:
public class MyService extends Service {private Downloadbinder Mbinder = new Downloadbinder (); class Downloadbinder extends Binder {public void Startdownload () {log.d ("MyService", "Startdownload executed");} public int getprogress () {log.d ("MyService", "getprogress executed"); return 0;}} @Overridepublic ibinder onbind (Intent Intent) {return mbinder;} ......}
can see, here we create a new Downloadbinder class, and let it inherit from Binder , and inside it provides a way to start the download and view the download progress. The specific logic code will not be written.
Next, an instance of Downloadbinder is created in MyService, , In this way, all the work in MyService is done.
How do you invoke these methods in the activity in the service?
For example, add 2 buttons to the mainactivity layout file. One for the binding service and one for canceling the service.
Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent " android:layout_height=" match_parent " android:orientation=" vertical "> ... <button android:id= "@+id/bind_service" android:layout_width= "match_parent" android:layout_ height= "Wrap_content" android:text= "Bind Service"/> <button android:id= "@+id/unbind_service" android:layout_width= "match_parent" android:layout_height= "wrap_content" android:text= "Unbind Service "/></linearlayout>
When an activity and service are bound, it is possible to invoke the methods provided by the binder in the service.
public class Mainactivity extends Activity implements Onclicklistener {Private button Startservice;private button Stopser Vice;private button bindservice;private button unbindservice;private myservice.downloadbinder downloadBinder;private Serviceconnection connection = new Serviceconnection () {@Overridepublic void onservicedisconnected (componentname name) {} @Overridepublic void onserviceconnected (componentname name, IBinder service) {Downloadbinder = ( Myservice.downloadbinder) service;downloadbinder.startdownload ();d ownloadbinder.getprogress ();}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); bindservice = (Button) Findviewbyid (r.id.bind_service); unbindservice = (Button) Findviewbyid (R.id.unbind_service); Bindservice.setonclicklistener (this); Unbindservice.setonclicklistener (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {... r.id.bind_service:intent bindintent = new Intent (This,Myservice.class); Bindservice (bindintent, Connection, bind_auto_create); Binding service Break;case R.id.unbind_service:unbindservice (connection); Unbind service Break;default:break;}}}
Here we first create an anonymous class of serviceconnection , which overrides the onserviceconnected () method and the onservicedisconnected () method, the two methods are called when the activity and the service are successfully bound and unbound. In the Onserviceconnected () method, we also get an example of downloadbinder by downward transformation, and with this example, the relationship between the activity and the service becomes very close. Now we can invoke any public method in the activity based on a specific scenario, that is, the function of what the command service does and what the service will do Downloadbinder. This is still a simple test, and the Downloadbinder startdownload () and Getprogress () methods are called in the Onserviceconnected () method.
Of course, activities and services are not yet bound, and this feature is done in the Click event of the Bind service button. As you can see, we're still building a intent object, and then calling the Bindservice () method to bind Mainactivity and MyService. The Bindservice () method receives three parameters, the first parameter is the intent object that was just built, the second argument is an instance of the Serviceconnection created earlier, and the third parameter is a flag bit, which is passed in Bind_auto_ Create means that the service is created automatically after the activity and the service are bound. This will cause the OnCreate () method in MyService to be executed, but the Onstartcommand () method will not execute.
And what if we want to unbind the activity from the service? Call the Unbindservice () method, which is the function that is implemented in the Click event of the Unbind Service button.
Note : Any service is common throughout the application, meaning that MyService can bind not only to mainactivity, but also to any other activity. And they can get to the same Downloadbinder instance once the bindings are complete.
4. Life cycle of the service
The service also has its own life cycle, and methods such as OnCreate (), Onstartcommand (), Onbind (), and OnDestroy (), which we used earlier, are methods that may be recalled during the life cycle of the service.
Once the context's StartService () method is called at any point in the project, the corresponding service will start up and callback the Onstartcommand () method. If the service has not been created before, the OnCreate () method will be executed prior to the Onstartcommand () method. After the service is started, it remains running until the StopService () or Stopself () method is called. Note Although the StartService () method is called once per call, Onstartcommand () executes once, but there is actually only one instance (singleton mode) for each service. So no matter how many times you call the StartService () method, simply call the StopService () or Stopself () method and the service will stop.
Alternatively, you can call the context's Bindservice () to get a persistent connection to a service, and then callback the Onbind () method in the service. Similarly, if the service has not been created before, the OnCreate () method is executed before the Onbind () method. The caller can then obtain an instance of the IBinder object returned in the Onbind () method so that it can communicate freely with the service. as long as the connection between the caller and the service is not broken, the service remains in a running state.
When the StartService () method is called and the StopService () method is called, the OnDestroy () method in the service executes, indicating that the service has been destroyed. Similarly, when the Bindservice () method is called and the Unbindservice () method is called, the OnDestroy () method executes, both of which are well understood. However, it is important to note that it is entirely possible for a service to call both the StartService () method and the Bindservice () method, so how can the service be destroyed? Depending on the mechanism of the Android system, a service can be destroyed only after it has been started or bound, and it has been in a state of operation and must not satisfy both of these conditions. Therefore, the OnDestroy () method executes when the StopService () and Unbindservice () methods are called simultaneously in this case.
5. Use Intentservice as much as possible
Why try to use Intentservice? This is mainly due to the following 2 reasons:
1. Service is running in the main thread, when we do some more time-consuming operation, it is easy to cause the program ANR, the former said, you can manually create a child thread, let it handle time-consuming logic;
2. When the service is finished, we will manually stop the service call StopService () or the Stopself () method
With Intentservice, you can do it without the hassle, intentservice the default is to turn on the child thread and stop the service automatically after the processing logic is completed
public class Myintentservice extends Intentservice {public myintentservice () {Super ("Myintentservice");//Call the parent class with a parameter constructor} @Overrideprotected void Onhandleintent (Intent Intent) {//print idlog.d of the current thread ("Myintentservice", "Thread ID is" + thread.curr Entthread (). GetId ());} @Overridepublic void OnDestroy () {Super.ondestroy (); LOG.D ("Myintentservice", "OnDestroy executed");}}
The first is to provide an argument-free constructor, and must call the parent class's parameter constructor inside it. Then to implement the abstract method of Onhandleintent () in the subclass, you can deal with some specific logic in this method, and do not worry about the ANR problem, because this method is already running in the sub-thread. To prove this, we have printed the ID of the current thread in the Onhandleintent () method. In addition, according to the characteristics of Intentservice, this service should be automatically stopped after the end of the run, so we have rewritten the OnDestroy () method, here also printed a line of logs to verify that the service is not stopped.
Add a button to the mainactivity and add a click event, adding the following code:
Prints the idlog.d of the main thread ("Mainactivity", "Thread ID is" + thread.currentthread (). GetId ()); Intent intentservice = new Intent (this, myintentservice.class); StartService (Intentservice);
Looking at the log output, you will find that not only the Myintentservice and Mainactivity are located in the same thread ID, but also the OnDestroy () method is executed, indicating that Myintentservice does stop automatically after it has finished running. The Intentservice is the same as the normal service, but it is more practical to set the thread and stop automatically.
6. The actual service
In this section, you can refer to another blog post that was previously written. http://blog.csdn.net/android_cmos/article/details/50775405
Resources:
Guo Lin: Chapter Nineth of the first line of code
The activity and service of those things