Detailed introduction based on Android service life cycle

Service concept and purpose:

The service in Android is different from activity. It can't interact with users and start itself. It is a program running in the background. If the service process doesn't end when we exit the application and it is still running in the background, when will we use the service? For example, when we play music, we may want to do other things while listening to music. When we quit the music playing application, if we don't use service, we won't hear songs, so we have to use service at this time. For example, when the data of an application is obtained through the network at different times (for a period of time) The data is different. At this time, we can use the service to update regularly in the background instead of getting it every time we open the application.

Service Lifecycle:

The life cycle of Android Service is not as complex as Activity. It only inherits onCreate (), onStart (), onDestroy (three). When we first launch Service, we have called onCreate (), onStart (two) methods. When we stop Service, we execute the onDestroy () method. Here we need to note that if the Service has already started, When we start the service again, we will not execute the oncreate () method, but directly execute the OnStart () method.

Communication between service and activity:

The back-end data of the service will eventually be presented on the front-end activity, because when starting the service, the system will restart a new process, which involves the problem of communication between different processes (Aidl). When we want to obtain the started service instance, we can use bindservice and unbindservice methods, which execute ibinder() and onund() in the service respectively method.

1. Add a class under the package of mainactivity

<service   android:name=".LService"   android:exported="true" > </service>

5. Run program

Program interface

Click start service

At this point, you can see that the running service has an lservice in the calling program settings

Click stopservice

Click bindservice

The service has been closed at this time

Click unbindservice

First click start service, then click bindservice and unbindservice

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