Android - Service Comprehensive Summary

1. Type of Service

  

Sort by location:

category the difference  advantage shortcoming   application
Local service (Local) The service is attached to the main process,  The service is attached to the main process instead of an independent process, which saves resources to a certain extent. In addition, the Local service does not need IPC or AIDL because it is in the same process. Corresponding bindService will be much more convenient.  After the main process is Killed, the service will be terminated.  Very common applications such as: HTC's music playback service, every day beautiful music playback service.
Remote service (Remote) The service is an independent process,  The service is an independent process, and the corresponding process name format is the package name plus the android:process string you specify. Because it is an independent process, when the process where the Activity is located is killed, the service is still running and is not affected by other processes, which is conducive to providing services for multiple processes with high flexibility.  The service is an independent process, it will take up some resources, and it is a little more troublesome to use AIDL for IPC.  Some services that provide system services are resident.

In fact, remote services are still rare, and are generally system services.

  

By run type:

category the difference application
Reception The Notification of ONGOING will be displayed in the notification column, When the service is terminated, the Notification in the notification column will also disappear, which has a certain notification effect for the user. Common such as music playback services.
Background Services The default service is the background service, that is, the notification of ONGOING will not be displayed in the notification column. When the service is terminated, the user will not see the effect. Certain services that do not require prompts to run or terminate, such as weather updates, date synchronization, mail synchronization, etc.

Some students may ask, can we create the Notification of ONGOING in the background service so that it becomes the foreground service? The answer is no, the foreground service needs to call startForeground (android 2.0 and later) or setForeground (android 2.0 earlier) after doing the above work to make the service a foreground service. The advantage of this is that when the service is forcibly terminated externally, the Notification of ONGOING will still be removed.

 

Classified by usage:

category the difference
service started by startService Mainly used to start a service to perform background tasks without communication. To stop the service use stopService
Services started by bindService The service started by this method is to communicate. Stop the service using unbindService
startService also bindService starts the service To stop the service, stepService and unbindService should be used at the same time

The service life cycle of the services started in the above three ways is also different, which will be given later.

 

2. The difference between Service and Thread

  

Many times, you may ask, why use Service instead of Thread, because using Thread is very convenient, and it is much more convenient than Service. I will explain it in detail below.

 

1). Thread: Thread is the smallest unit of program execution, and it is the basic unit for allocating CPU. You can use Thread to perform some asynchronous operations.

2). Service: Service is a mechanism of android. When it is running, if it is Local Service, then the corresponding Service is running on the main thread of the main process. Such as: onCreate, onStart These functions are run on the main thread of the main process when they are called by the system. If it is a Remote Service, then the corresponding Service runs on the main thread of an independent process. So please don't understand Service as a thread, it has nothing to do with threads!

  

In this case, why do we use Service? In fact, this is related to the system mechanism of android, let's take Thread as an example. The operation of Thread is independent of Activity, that is to say, after an Activity is finished, if you do not actively stop Thread or the run method in Thread has not been executed, Thread will continue to execute. So there is a problem here: when the Activity is finished, you no longer hold a reference to the Thread. On the other hand, you have no way to control the same Thread in different Activities.

  

For example: If your Thread needs to connect to the server to do some synchronization at regular intervals, the Thread needs to be running even when the Activity is not started. At this time, when you start an Activity, there is no way to control the previously created Thread in the Activity. Therefore, you need to create and start a Service, create, run and control the Thread in the Service, which solves the problem (because any Activity can control the same Service, and the system will only create an instance of the corresponding Service).

  

So you can think of Service as a message service, and you can call Context.startService, Context.stopService, Context.bindService, Context.unbindService in any place with Context to control it, you can also register BroadcastReceiver in Service, Control it by sending a broadcast elsewhere, which of course Thread can't do.

  

3. Service life cycle

 

onCreate  onStart  onDestroy  onBind 

1). The life cycle of the started service: If a Service is started by an Activity by calling the Context.startService method, then the Service runs in the background regardless of whether an Activity is bound to the Service using bindService or unbindService is unbound. If a Service is started multiple times by the startService method, the onCreate method will only be called once, onStart will be called multiple times (corresponding to the number of times startService is called), and the system will only create one instance of the Service (so you should know that you only need one instance) stopService call). The Service will always run in the background, regardless of whether the Activity of the corresponding program is running, until stopService or its own stopSelf method is called. Of course, if the system resources are insufficient, the android system may also end the service.

 

2). The life cycle of the bound service: If a Service is bound and started by an Activity calling the Context.bindService method, no matter how many times bindService is called, the onCreate method will only be called once, and the onStart method will never be called. transfer. After the connection is established, the Service will always run, unless the Context.unbindService is called to disconnect the connection or the Context that called bindService before does not exist (such as when the Activity is finished), the system will automatically stop the Service, and the corresponding onDestroy will be called.

 

3). The life cycle of the service that is started and bound: If a Service is started and bound again, the Service will always run in the background. And no matter how it is called, onCreate will always be called only once, and the onStart of the Service will be called as many times as the startService is called. Calling unbindService will not stop the Service, but must call stopService or stopSelf of the Service to stop the service.

 

4). Clear the service when the service is stopped: when a Service is terminated (1, call stopService; 2, call stopSelf; 3, no longer have bound connections (not started)), the onDestroy method will be called , where you should do some cleanup, such as stopping threads created and running in the Service.

 

pay attention:

1. You should know that when calling bindService to bind to the Service, you should ensure that you call unbindService somewhere to unbind it (although the binding will be automatically released when the Activity is finished, and the Service will automatically stop);

2. You should note that after starting the service with startService, you must use stopService to stop the service, regardless of whether you use bindService or not; 

3. Use startService and bindService at the same time It should be noted that the termination of the Service requires the simultaneous calls of unbindService and stopService to terminate the Service. Regardless of the calling sequence of startService and bindService, if the unbindService is called first, the service will not be automatically terminated, and then stopService is called. The service will stop. If stopService is called first, the service will not be terminated, and the service will stop automatically after calling unbindService or the context that called bindService before does not exist (such as when the Activity is finished).

4. When rotating the mobile phone screen, when the mobile phone screen is changing between "horizontal" and "vertical", if your Activity will automatically rotate, the rotation is actually the re-creation of the Activity, so the use of bindService before the rotation is established. The connection will be disconnected (Context does not exist), and the life cycle of the corresponding service is the same as above.

5. In sdk 2.0 and later versions, the corresponding onStart has been rejected and changed to onStartCommand, but the previous onStart is still valid. This means that if you develop an application with sdk 2.0 and later, you should use onStartCommand instead of onStart.

 

4. startService starts the service

  

To start a service with startService, the work we need to do is as simple as Local or Remote. Of course, remember to register the service in Androidmanifest.xml.

According to the above life cycle, we will give the code framework in the Service:

The corresponding life cycle system callback function has been described above, just add the appropriate code in the corresponding place. Here is the code to start and stop the Service:

The corresponding Intent is the Intent that marks the service class.

 

5. Binding Local and Remote services

 

Also remember to register service in Androidmanifest.xml

1). Binding of Local service: The binding of Local service is relatively simple. First, in Service, we need to implement the abstract method onBind of Service, and return an object that implements the IBinder interface.

Code in Service:

The key point of the above code is that the onBind(Intent) method returns an object that implements the IBinder interface, which will be used to bind the Activity of the Service to communicate with the Local Service. Here is the code in the Activity:

In the Activity, we use the ServiceConnection interface to get callbacks for connection establishment and unexpected connection loss. bindService has three parameters, the first is the Intent used to distinguish Service is consistent with the Intent in startService, the second is the object that implements the ServiceConnection interface, and the last is the flag bit. There are two flags, BIND_DEBUG_UNBIND and BIND_AUTO_CREATE, the former is used for debugging (details can be clearly described in the javadoc above), and the latter is used by default. unbindService unbinds, the parameter is the previously created ServiceConnection interface object. Also, calling unbindService multiple times to release the same connection throws an exception, so I created a boolean variable to determine if unbindService has already been called.

operation result:

 

2). Remote service binding: Remote service binding requires the use of android's IPC mechanism because the service is in another process. This will be a long topic again, so I plan to write another IPC mechanism analysis of android, and elaborate in it, and then update the link here, so stay tuned.

 

pay attention:

1. If Service.onBind returns null, calling bindService will start the Service, but will not connect the Service, so ServiceConnection.onServiceConnected will not be called, but you still need to use the unbindService function to disconnect it, so that the Service will stop.

 

 6. Create a foreground service

  

The advantages of the foreground service have been explained above, but to set the service as the foreground service, we need to pay attention to the methods used in sdk 2.0 and later versions are startForeground and stopForeground, the previous version used setForeground, so if your application requires the minimum operating environment If it is 2.0, then the new method can be directly used here. If the operating environment is below 2.0, then in order to ensure backward compatibility, reflection technology must be used to call the new method.

Here is the code I retyped from ApiDemos, with some changes made so it's more illustrative:

pay attention:

  1. Use startForeground, if the id is 0, the notification will not be displayed.

  

7. When to use startService or bindService or use both startService and bindService

  

If you just want to start a background service for a long-term task then use startService. If you want to get in touch with the running Service, there are two ways, one is to use broadcast, and the other is to use bindService. The disadvantage of the former is that if the communication is frequent, it is easy to cause performance problems, and the BroadcastReceiver itself executes the code The time is very short (maybe halfway through, the code behind will not be executed), and the latter does not have these problems, so we definitely choose to use bindService (this time you are using startService and bindService at the same time, which is in Activity It is quite useful to update some operational status of the Service in ). In addition, if your service only exposes a remote interface for the connected client (Android's Service is a C/S architecture) to remotely call the execution method. At this time, you can not let the service run from the beginning, but only use bindService, so that an instance of the service will be created and run it when the first bindService is executed, which will save a lot of system resources, especially if your service is a Remote Service , then the effect will be more obvious (of course it will take some time when the Service is created, you should pay attention to this).

  

 

8. Common options for Service element in AndroidManifest.xml

android:name ------------- service class name

android:label -------------- The name of the service, if this item is not set, the service name displayed by default is the class name

android:icon -------------- The icon of the service

android:permission ------- Declare the permission of this service, which means that only applications that provide this permission can control or connect to this service

android:process ---------- Indicates whether the service is running in another process. If this item is set, this string will be added to the package name to indicate the name of another process

android:enabled ---------- If this item is set to true, then the Service will be started by the system by default, if not set the default item is false

android:exported --------- Indicates whether the service can be controlled or connected by other applications, if not set, the default is false

 

The code download address of this article: http://files.cnblogs.com/newcj/ServiceTest.zip

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324931202&siteId=291194637