Detailed explanation of service in Android

1. Concept: (1). Service can be said to be an activity running in the background. It is not a separate process. It only needs the application to tell it what to do in the background. (2) If it realizes the interaction with users, it needs to receive the display through the notification bar or by sending broadcast and UI. (3) It is widely used, especially in the framework layer. It is more used to call system services. 2. Functions: (1) it is used to handle some background operations that do not interfere with users' use. For example, download and obtain through the network. When playing music, it can be opened through intent, and can also be bound to the host object (caller, such as activity). (2) If the activity displays the information of the foreground page, the service operates in the background. If the service interacts with the foreground UI, you can send a broadcast or notification bar. 3. Life cycle: (1). The overall life time of the service starts when oncreate() is called and ends when ondestroy() returns. Like activity, service initializes in oncreate() and releases remaining resources in ondestroy(). (2) . * * startservice() method: * * oncreate() - > onstartcommand() - > onstart() - > ondestroy() (3). * * bindservice() method: * * oncreate() - > onbinder() - > onunbind() - > ondestroy(). The onunbind () method ends when it returns.

4. Startup method: (1). The service cannot run by itself and needs to be called through an activity or other context object. (2) . service can be started in two ways: context. Startservice() and context. Bindservice(). If there are time-consuming operations in the oncreate() method or onstart() method of the service, start a new thread. Start the service in the above two ways where it is needed. Note: the startservice method is usually used. You can put some time-consuming tasks in the background for processing. When the processing is completed, you can notify the foreground through the broadcast or notification bar.

5. The following code is used for in-depth understanding:

(1) . mainactivity.java class:

(2) . myservice. Java class:

(3).AndroidManifest.xml

Startservice method: (1) when pressing the startservice button:

(2) . continue to press the startservice button as follows:

Bindservice method:

(1) . press the bindservice button as follows:

(2) . continue to press the bindservice button as follows:

(3) . press the startservice button first and then the bindservice button as follows:

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
分享
二维码
< <上一篇
下一篇>>