Android improved service usage example analysis

The previous article introduced the use of activity and intent. This article will introduce service. If activity is compared to a foreground program, then service is a background program, and the whole life cycle of service will only be executed in the background. Like activity, service is also called by intent. To add a service in the project, first create a class that inherits the service, and then add it to the service tag in androidmanifest.xml - > Application - > application nodes.

Service should be started by activity through startservice or bindservice, and intent is responsible for passing parameters. First, post the screenshot of the program running as follows:

This article mainly explains the invocation of service and its life cycle.

The above figure shows the service status change of stopservice after startservice.

The above figure shows the change of service status after bindservice and then unbindservice.

Both startservice and bindservice can start service, so what's the difference between them? The difference between them is to change the service cycle. The service started by startservice must have stopservice to end the service. If stopservice is not called, the activity will end and the service will still be running. The service started by bindservice can be ended by unbindservice or automatically after the activity ends (ondestroy).

The above figure shows the service status change of activity. Finish() after startservice, and the service is still running.

The above figure shows the service status change of activity. Finish() after bindservice, and the service will finally unbindservice automatically.

The main.xml code is as follows:

The source code of testservice.java is as follows:

The source code of myservice.java is 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
分享
二维码
< <上一篇
下一篇>>