Android Four components-service not detailed

Source: Internet
Author: User

It was almost a year since the last article. This time, I want to clarify some of the more important points of service.


As for what is a service, I do not want to discuss more, I just want to clearly confirm that a few questions:

1. What is the service life cycle?

2. How does activity make service work?

3. Is there a relationship between service and thread?

4. What is a remote service?

5, the use of aidl?

6, front desk service?

First, life cycle

If need figure, can Baidu, many. I am here to run the code directly to play log.

1. StartService () Start service


The sequence of operations is:

StartService (Intent), the service executes OnCreate ()------> Onstartcommand ()------> OnStart ().

StopService (Intent), the service executes OnDestroy () accordingly.

StartService (Intent), the service executes OnCreate ()------> Onstartcommand ()------> OnStart ().

StartService (Intent), the service performs onstartcommand ()------> OnStart () accordingly.

StopService (Intent), the service executes OnDestroy () accordingly.


As you can see here, onCreate () will only execute once, that is, the first time the service is started, the onCreate () will not be executed until the destroy has been restarted.


2, Bindservice () Start Service First Note: If you use Bindservice () to start the service, you need to instantiate an interface, serviceconnection. Then implement the interface inside the two methods, onservicedisconnected () and onserviceconnected (). Normally only the onserviceconnected () method is executed, and another method executes when the system is out of memory forcing the recycle service to cause connection to break.
Private Serviceconnection connection = new Serviceconnection () {@Overridepublic void onservicedisconnected ( ComponentName name) {//TODO auto-generated method stub} @Overridepublic void Onserviceconnected (componentname name, IBinder service) {//TODO auto-generated method Stubdebuglog ("onserviceconnected ()");}};

Bindservice's prototype:

Parameters: Service:intent object that describes which serviceconn to start: The connection created above flags: a flag that is generally used for automatic creation (bind_auto_create)
Unbindservice's prototype:
public void Unbindservice (Serviceconnection conn)

Parameter: Conn: is the connection established above, if Unbindservice continues after unbind will throw run exception, terminate the program.
Log as follows:



Sequence of operations:
Bindservice (Intent3, Connection, bind_auto_create): Service Execution Order: onCreate ()------>onbind ()------> Onserviceconnected ()
Unbindservice (connection): Service Execution Order: Onunbind ()-------> OnDestroy ()
StartService (Intent): Service Execution Order: onCreate ()------> Onstartcommand ()-------->onstart () bindservice (Intent3, Connection, bind_auto_create): Service Execution Order: Onbind ()------> onserviceconnected ()
Unbindservice (connection): Service Execution Order: Onunbind ()
StopService (Intent): Service Execution Order: OnDestroy ()

When the service life cycle is known, you should also know which method to write if you need to use the service.

Second, how does the activity make the service serve itself? The intent is the intent of the parameters in the Onstartcommand () and OnStart () functions in the service when starting the services with intent when the activity is not speaking to service value. Therefore, the simple value can be directly used intent. Here's how to make a call to a method? Make service real services activity. 1. Use the Binder class to first create a class in the service class that inherits from Binder, such as:
public class Mybinder extends binder{public void Startdownload () {debuglog ("Start download ..."); Gets the current MyService instance public MyService GetService () {return myservice.this;}}
There is a startdownload () method inside this class that simulates the download. Returns the class instance in the Onbinder () method:
Public IBinder Onbind (Intent Intent) {//TODO auto-generated method Stubdebuglog ("Onbind ()"); return new Mybinder ();


In the serviceconnection implementation of the Onserviceconnected () method, you get an instance of this class, and you can then execute the method inside.

Myservice.mybinder Mybinder = (mybinder) service;mybinder.startdownload ();

This method simply allows the activity to invoke the method inside the service.
2. Use of Radio
As for the activity and service which end does the receiver which side does the transmitter end, depends on the actual situation. Here is the activity to send the broadcast, service to listen. This method can be used in music player, such as to let the service listening system broadcast, if the call to pause playback. Wait a minute.
Simply write here, just provide ideas.
Dynamically register the broadcast within the service:
Private Broadcastreceiver Myreceiver = new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent in Tent) {//TODO auto-generated method Stubstring string = Intent.getstringextra ("main");D Ebuglog ("string:" +string);}};

Register in the OnCreate () function in the service:
Intentfilter filter = new Intentfilter (); Filter.addaction ("Com.fleur.mybroadcast"); Registerreceiver (Myreceiver, Filter);D Ebuglog ("registerreceiver success");
Anti-registration in the service's OnDestroy () function:
Unregisterreceiver (Myreceiver);

dynamically registered broadcasts must not forget the anti-registration.
You can then send the broadcast in the activity. Like what:
Case R.id.button8:intent intent5 = new Intent ("Com.fleur.mybroadcast"); Intent5.putextra ("main", "this broadcast are from Mainactivity "); Sendbroadcast (intent5); break;

Log as follows:

3. Using callbacks I always felt that the callback was a magical thing. If you don't understand the callback, you can read this article: http://blog.csdn.net/xiaanming/article/details/8703708
Callbacks resolve the service to invoke the activity inside the method. First create the callback interface (a separate interface file):
Public interface Onprogresslistener {public void onprogress (int progress);

inside the interface is the callback method.
In the service life is an interface variable, and then provides a method for an externally registered interface. Like what:
Callback interface for update progress private Onprogresslistener onprogresslistener;/** * method of registering Callback interface * @param onprogresslistener */public void Setonprogresslistener (Onprogresslistener onprogresslistener) {this.onprogresslistener = OnProgressListener;}
Then the service inside declares a method that still simulates the download:
public void Startdownload () {new Thread () {@Overridepublic void run () {while (Progress < max_progress) {progress + = 5;// Tells the caller if (onprogresslistener!=null) {onprogresslistener.onprogress (progress) when the progress has changed;} try {sleep (+),} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}. Start ();}

Note that this is the method inside the service, not the method inside the Mybinder class.
In activity: First declare an object of MyService class, then get this object in connection, register callback interface, implement callback method. As follows:
public void onserviceconnected (componentname name, IBinder service) {//TODO auto-generated method Stubdebuglog (" Onserviceconnected () "); Mybinder = (mybinder) Service;myservice = Mybinder.getservice (); Myservice.setonprogresslistener (New Onprogresslistener () {@Overridepublic void onprogress (int progress) {//TODO Auto-generated Method Stubprogressbar.setprogress (progress);});}
Then write a button control yourself and use the resulting MyService object to invoke the Startdownload () method to implement the callback.
Myservice.startdownload ();

There are two ways to communicate activity between different processes, one is to use Messenger, and the other is to use Aidl. Let's not talk about it here.

Is there a relationship between service and thread?
Service is run in the background without the user interface, a new thread is also not visible to the user, running in the background. But the service and thread really does not have a relationship, for the ordinary local service, he and the activity is running in the same process inside the main line thread, that is, the service is the main thread, UI thread, can not be time-consuming operation. What if I want to go back to the Web to download it? Simple, open a new thread in the service, no difference from opening a new thread in the activity.

Iv. What is a remote service? Normally the service we declare in the Activitymanifest.xml file is LocalService, that is, local services. That is, you can only serve the application (APP). However, some service is to serve other apps, then should use remote service, in fact, only need to activitymanifest.xml file declaration service when this write:
<service android:name= "Com.fleur.service.MyRemoteService"            android:process= ": remote" >            < Intent-filter >                <action android:name= "Com.fleur.service.MyRemoteService"/>            </intent-filter >
Added a word: android:process= ": remote" becomes the service.
Note here that the remote service is not in the same process as the activity, using StartService () to print the log as follows: This will not cause a ANR problem if the remote service takes a time-consuming operation. However, using a remote service, you cannot use Bindservice () directly, and you cannot communicate with activity like LocalService. At this point, you need to use AIDL for interprocess communication.
or you can not use the remote service do not use it.
V. Use of aidl? First create a. aidl file, which uses Java syntax to write an interface. After saving, Java files are automatically generated under Gen. As follows:
Package Com.fleur.service;interface myaidlservice{string touppercase (String str);}

In the remote service instance a Binder object, the method of implementing the interface. As follows:
Import com.fleur.service.MyAIDLService.Stub;
Stub mbinder = new stub () {@Overridepublic string touppercase (String str) throws RemoteException {//TODO auto-generated m Ethod stubif (str!=null) {return str.touppercase ();} return null;}};
In fact, the stub is in the Aidl file, it inherits the binder implementation of our own written interface. Then return this object in Onbind ().


In the activity of the same instance serviceconnected interface, declare a just write interface object, in onserviceconnected inside get instance.
Private Myaidlservice myaidlservice;private Serviceconnection conn = new Serviceconnection () {@Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated method stub} @Overridepublic void Onserviceconnected ( ComponentName name, IBinder service) {//TODO auto-generated Method Stubmyaidlservice = MyAIDLService.Stub.asInterface ( Service); try {String upperstr = myaidlservice.touppercase ("Hello World");D ebuglog ("upperstr =" +upperstr);} catch (RemoteException e) {//TODO auto-generated catch Blocke.printstacktrace ();}};
It's OK to go to the bindservice. The communication between different processes is realized.
Six, the front desk Serviceservice priority is particularly low, if memory is not easy to recycle, but sometimes our app is very dependent on service, do not want to recycle, if recycled, I this app is not interesting, then you can use the front desk service. In fact, it is very simple, in the service of the OnCreate method to write:
Notification Notification = new Notification (R.drawable.ic_launcher, "Android_component", System.currenttimemillis () ); Intent notificationintent = new Intent (this,mainactivity.class); Pendingintent pendingintent = pendingintent.getactivity (this, 0, notificationintent, 0); Notification.setlatesteventinfo (This, "title of Notification", "content of Notification", pendingintent); Startforeground (1, notification);

The most critical is the last sentence, the Startforeground () method. When you start the service again, you will find the notification bar an icon, which is the "front service" that you run in the background. When the service is destroyed, the foreground service is destroyed accordingly. such as music player Ah, weather class Ah, the service depends on the higher can consider the front service.

Some things you understand but may not understand, referring to a blog: http://www.360doc.com/content/14/0415/18/2793098_369238276.shtml and then add their own understanding.
For the service some blind spots or important points, has not been summed up before, this is really a serious summary of the back. In addition to this there is a front desk service, you can see for yourself.
Service is just one of many important points that I need to summarize in Android. Next, we will continue to summarize.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Four components-service not detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.