Example code of local service of anroid’s four component services

Service is one of the four components of Android. Like activity, it represents executable programs. However, unlike activity, service has an operable user interface. It always runs in the background. In plain words:

If an application wants to present actionable information to users at runtime, it should select activity. If not, it should select service.

The service life cycle is as follows:

The service will only be created once and destroyed once. So, how to create a local service?

The implementation code is as follows:

To declare a service, you must configure it in manifests

Android: exported = "true" setting this property means that others can use your service.

Another small point to note is that in myservice, you can see that I used a sub thread to help me implement work when I started. Why didn't I directly write the code of the for loop in the onstartcommand method, because the error of no response of the anr program will be reported in onstartcommand. When you leave everything to the main thread, it will overflow the memory of the main thread and explode. At this time, intentservice can also be used to replace service.

Using this is relatively easy. Intentservice is a subclass of service. It uses worker threads to process all startup requests one by one.

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