Comprehensive summary of service in Android

Comprehensively summarize the use methods of Android service, and the specific contents are as follows

1. Type of service

Classification by operation location:

In fact, remote services are rare, and are generally system services. Classification by operation type:

Some students may ask, can we create our own ongoing notification as the background service? The answer is No. after doing the above work, the foreground service needs to call startforegroup (Android 2.0 and later versions) or setforegroup (Android 2.0 and earlier versions) to make the service a foreground service. The advantage of this is that when the service is terminated by external force, the ongoing notification will still be removed.

Classification by usage:

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

2. Difference between service and thread

Many times, you may ask why you use service instead of thread, because using thread is very convenient and much more convenient than service. Let me explain it in detail below.

1) . thread: thread is the smallest unit of program execution. It is the basic unit of CPU allocation. Thread can be used to perform some asynchronous operations.

2) . service: service is a mechanism of Android. When it runs, if it is a local service, the corresponding service runs on the main thread of the main process. For example, oncreate and OnStart functions run on the main thread of the main process when called by the system. If it is a remote service, the corresponding service runs on the main thread of an independent process. Therefore, please do not understand service as a thread. It has nothing to do with threads for half a dime!

In that case, why should we use service? In fact, this is related to the system mechanism of Android. Let's take thread first. The operation of the thread is independent of the activity, that is, after an activity is finished, if you do not actively stop the thread or the run method in the thread is not completed, the thread will be executed all the time. Therefore, there will be a problem: after the activity is finished, you no longer hold the reference of the thread. On the other hand, you cannot control the same thread in different activities.

For example: if your thread needs to connect to the server for some synchronization at regular intervals, the thread needs to run when the activity does not start. 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 this problem (because any activity can control the same service, and the system will only create an instance of the corresponding service).

Therefore, you can think of service as a message service, and you can call context.startservice, context.stopservice, context.bindservice and context.unbindservice wherever there is context to control it. You can also register broadcastreceiver in service and control it by sending broadcast in other places, Of course, thread can't do all this.

3. Service Lifecycle

onCreate  onStart  onDestroy  onBind

1) . life cycle of the started service: if a service is started by an activity calling the context.startservice method, the service runs in the background regardless of whether an activity uses bindservice to bind or unbindservice to unbind 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 times startservice is called), and the system will only create one instance of the service (so you should know that only one stopservice call is required). The service will always run in the background, regardless of whether the activity of the corresponding program is running or not, 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) . life cycle of bound service: if a service is bound and started by an activity calling the context.bindservice method, the oncreate method will only be called once no matter how many times bindservice is called, and the OnStart method will never be called. When the connection is established, the Service will continue to run. Unless the Context disconnects or the Context that calls bindService before does not exist, such as when Activity is finish, the system will automatically stop Service, and onDestroy will be called.

3) . 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. No matter how it is called, oncreate will always be called only once. The number of calls corresponding to startservice will be the number of calls to OnStart of the service. 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. There is no bound connection (not started)), the ondestroy method will be called. Here you should do some clearing work, such as stopping the threads created and running in the service.

Special attention:

1. You should know that when calling bindservice to bind to a service, you should ensure that you call unbindservice to unbind somewhere (although the binding will be automatically released when the activity is finished, and the service will stop automatically);

2. You should note that after using startservice to start the service, you must use stopservice to stop the service, whether you use bindservice or not;

3. When using startservice and bindservice at the same time, it should be noted that the service can be terminated only when unbindservice and stopservice are called at the same time. Regardless of the call order of startservice and bindservice, if unbindservice is called first, the service will not be terminated automatically, and then stopservice will be called, If you call stopService first, the service will not terminate at the same time, and then the unbindService or the Context before calling bindService does not exist, such as when Activity is finish, then the service will stop automatically.

4. When rotating the mobile phone screen, when the mobile phone screen is changing from "horizontal" to "vertical", if your activity will rotate automatically, the rotation is actually the re creation of the activity. Therefore, the connection established using bindservice before rotation will be disconnected (the 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 your application uses SDK 2.0 and later, you should use onstartcommand instead of OnStart.

4. Startservice start service

To start the service with startservice, whether local or remote, we need to do the same simple work. Of course, remember to register the service in androidmanifest. XML.

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

The corresponding life cycle system callback function has been described above. Just add appropriate code in the corresponding place. The following is the code to start and stop the service:

The corresponding intent is the intent of the flag service class.

5. Local and remote service binding

Also remember to register the service in androidmanifest. XML

1) . local service binding: 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 implementing 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 and communicate with the local service. Here is the code in the activity:

In the activity, we use the serviceconnection interface to get the callback for establishing the connection and accidental loss of the connection. Bindservice has three parameters. The first is to distinguish the consistency between the intention of service and that 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 (see Javadoc for details, which is clearly described above), and the latter is used by default. Unbindservice unbinds, and the parameter is the serviceconnection interface object created earlier. In addition, calling unbindservice multiple times to release the same connection will throw an exception, so I created a boolean variable to determine whether unbindservice has been called.

Operation results:

2) . remote service binding: remote service binding requires Android IPC mechanism because the service is in another process. This will be another long topic, so I'm going to write another analysis of Android's IPC mechanism, elaborate on it, and then update the link here. Please pay attention.

Special attention:

1. If service.onbind returns null, calling bindservice will start the service, but it will not connect to the service. Therefore, serviceconnection.onserviceconnected will not be called, but you still need to disconnect it with the unbindservice function so that the service will stop.

6. Create foreground service

The advantages of the foreground service have been described above, but to set the service as the foreground service, we need to note that the methods used in SDK 2.0 and later versions are startforegroup and stopforegroup, and the previous versions used setforegroup. Therefore, if the minimum operating environment requirement of your application is 2.0, you can directly use the new method here, If the running environment is below 2.0, in order to ensure backward compatibility, reflection technology must be used to call new methods.

The following is the code I re typed after apidemos, which has been modified in some places, so it is more illustrative:

Special attention:

1. Using startforegroup, if the ID is 0, the notification will not be displayed.

7. When to use startservice or bindservice or both startservice and bindservice

If you just want to start a background service to carry out a task for a long time, you can use startservice. If you want to get in touch with the running service, there are two methods: 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 code execution time of the broadcastreceiver itself is very short (maybe the later code will not be executed when it is half executed), The latter does not have these problems, so we must choose to use bindservice (at this time, you are using startservice and bindservice at the same time, which is very useful to update some running states of the service in the activity). In addition, if your service only exposes a remote interface for the connected customer service end (Android service is C / S architecture) to remotely call and execute methods. At this time, you can only use bindservice instead of running the service at the beginning. In this way, you can create an instance of the service to run it at the first bindservice, which will save a lot of system resources. Especially if your service is a remote service, the effect will be more obvious (of course, it will take some time to create the service, you should pay attention to this) 。

8. Common options for the 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 ------------- icon of the service

Android: permission ------- declare the permission of this service, which means that only the application providing 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 after the package name to indicate the name of another process

Android: enabled ------------- if this item is set to true, the service will be started by the system by default. If this item is not set, it is false by default

Android: exported ------------- indicates whether the service can be controlled or connected by other applications. If not set, this item is false by default

Download address: ServiceTest

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>