[Comprehensive summary of the four major components - Service]

A comprehensive summary of Service in Android

1. Types of Services

  • [Classification by operating location: divided into local service and remote service]

    • Local service (Local): This service is attached to the main process,

      • Advantages:
        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 require IPC or AIDL because it is in the same process. The corresponding bindService will be much more convenient.

      • Disadvantage: After the main process is killed, the service will be terminated.

      • Application Scenarios: Very common applications such as: HTC's music playback service, Tiantiandongting music playback service.

    • Remote service (Remote): This service is an independent process,

      • Advantages:
        The service is an independent process, and the corresponding process name format is: the package name plus the android:process string you specified. Since it is an independent process,
        when the process where the Activity is located is killed, the service is still running and will not be affected by other processes, which is conducive to providing services for multiple processes with high flexibility.

      • Disadvantages: 
        This service is an independent process, which will occupy certain resources, and using AIDL for IPC is a little troublesome.

        • Application: Some services that provide system services, such services are resident.
  • [Categorized by operation type: divided into foreground and background services]

    • 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 users.

      • Application: Common such as music playback services.

    • Background service:
      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 cannot see the effect.

      • Application:
        Certain services that do not need to run or terminate prompts, such as weather update, date synchronization, email synchronization, etc.

      • Background service We can create ONGOING (uninterrupted) Notification so that it becomes a foreground service?

        • The answer is no, the foreground service needs to call startForeground (android 2.0 and later versions) or setForeground (android 2.0 and later versions) to make the service a foreground service after doing the above work. The advantage of this is that when the service is terminated externally, the ONGOING Notification will still be removed.
  • [Classified by usage]:

    • The service started by startService
      is mainly used to start a service to perform background tasks without communication. To stop a service use stopService

    • The service started by bindService
      The service started by this method needs to communicate. To stop a service use unbindService

    • startService is also the service started by bindService.
      To stop the service, you should use stepService and unbindService at the same time.

    [The life cycle of services started in the above three ways is also different].

2. [The difference between Service and Thread]

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

  2. Service: Service is a mechanism of android. When it is running, if it is a Local Service, then the corresponding Service is running on the main thread of the main process. Such as: onCreate, onStart These functions are all 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!

  3. 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 is not executed, Thread will continue to execute. So there will be 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 for some kind of 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).

  4. Therefore, Service can be imagined 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, in Other places control it by sending broadcast, of course, these are things that Thread cannot 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 calling the Context.startService method, the Service will run in the background no matter whether there is an Activity using bindService to bind or unbindService to unbind to the Service. 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 calls to startService), and the system will only create one instance of the Service (so you should know that only one stopService call). The Service will always run in the background, regardless of whether the corresponding program's Activity is running, until it is called stopService, or its own stopSelf method. 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 the bindService is called, the onCreate method will only be called once, and the onStart method will never be called. After the connection is established, the Service will keep running, unless the Context.unbindService is called to disconnect or the Context that called the 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 a 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 only be called once, and how many times the onStart of the Service will be called corresponding to how many times startService is called. Calling unbindService will not stop the Service, but you 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, there is no longer a bound connection (not started)), the onDestroy method will be called, here You should do some cleaning work, such as stopping the threads created and running in the Service.

pay attention:

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

  2. It should be noted that after using startService to start the service, be sure to use stopService to stop the service, no matter whether you use bindService or not;

  3. When using startService and bindService at the same time, it should be noted that the termination of the Service requires unbindService and stopService to be called at the same time to terminate the Service. Regardless of the calling order of startService and bindService, if the unbindService is called first, the service will not be automatically terminated at this time, and then the service will be called after stopService It will stop. If stopService is called first, the service will not be terminated at this time, and then 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 screen of the mobile phone, when the screen of the mobile phone is changing between "horizontal" and "vertical", if your Activity will automatically rotate at this time, the rotation is actually a re-creation of the Activity, so the connection established using bindService before the rotation 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 deprecated and changed to onStartCommand, but the previous onStart is still valid. This means that if you develop an application using sdk 2.0 and later, then you should use onStartCommand instead of onStart.

4. Common options of Service element in AndroidManifest.xml

android:name  -------------  服务类名

android:label  --------------  服务的名字,如果此项不设置,那么默认显示的服务名则为类名

android:icon  --------------  服务的图标

android:permission  -------  申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务

android:process  ----------  表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字

android:enabled  ----------  如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false

android:exported  ---------  表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false

Guess you like

Origin blog.csdn.net/UserFrank/article/details/129204498