Detailed explanation of service in Android (II)

This paper analyzes the service in android in detail. Share with you for your reference, as follows:

In the previous article "detailed explanation of service in Android (I)", we introduced the start and stop of service, which is to call the startservice and stopservice methods of context. There is another start mode and stop mode, that is, bind service and unbind service. This mode makes the relationship between the service and the activity that starts the service closer, and you can tell the service what to do in the activity.

To illustrate this situation, do the following:

1. Modify service class myservice

In the service class, an internal class musicbinder is added. In this internal class, we simulate two methods. At the same time, we return our internal class instance in the onbind method.

2. Modify layout file activity_ main.xml

Two buttons are added: bind service and unbind service.

3. Modify mainactivity.java file

In this class, an anonymous class of ServiceConnection is created, that is, the work that needs to be done when the activity and service establish a connection. In the onServiceConnected method, we carry out the type conversion of the binding service, and then call the corresponding business logic method.

The binding stone of activity and service is implemented in onclick method: bind with bindservice method to bind mainactivity activity and myservice service together. The third parameter is a flag bit, which indicates that the service is automatically created after the activity and service are bound.

Unbinding activities and services uses unbindservice.

4. Testing

Click "bind service", as follows:

The ready and play methods will be executed at the same time, and will be printed in the log.

Click "unbind service", as follows:

Summary: the process of binding services in this way is as follows:

Bindservice method of context -- oncreate method of service -- onbind method of service -- service running.

The unbinding service process is as follows:

Service running -- unbindservice method of context -- ondestroy method of service -- service stop.

For more information about Android components, readers who are interested can see the special topic of this site: summary of the usage of Android basic components

I hope this article will help you in Android programming.

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