Sunday, February 1, 2015
Android beginner tutorial Part 60 Introduction to Services
A Service in Android is a component similar to Activity. The difference between the two is that a Service runs in the background, it has no user interface whatsoever. Because of that, they are used to perform actions that dont need user interaction. A Service keeps running until it is stopped by something else or if it stops itself.
Using Intents, applications can connect and interact with Services. There can be more than one application connected to a single Service.
Just like the Activity class, Service has lifecycle methods. The 3 main ones are onCreate(), onStartCommant() and onDestroy().
A Service can be started by an application using Context.startService() method. It can be stopped using Context.stopService().
A Service can stop itself using Service.stopSelf() or Service.stopSelfResult() methods.
It is possible to connect to a running Service and use that connection to interact with the Service. The connection is established using Context.bindService() method and stopped using Context.unbindService().
If a Service has been stopped, it can be resumed using the bindService() method.
The onStartCommand() function is called by the system every time the service is explicitly called using the startService() method. It provides the arguments that are passed to the method, as well as a unique token of the start request. The onCreate() and onDestroy() methods are called in all Services regardless of whether they were added using startService() or bindService() methods.
Any Service can potentially interact with the user, because any Service can receive client requests. If a Service allows other applications to connect to it, its binding is done using these methods: onBind(), onUnbind() and onRebind(). They all receive Intent objects as parameters.
The Intent thats sent to the onBind() function is the one that was used in the bindService() function. The Intent thats sent to the onUnbind() function is the one that was used in unbindService().
The onBind() method returns the connection channel, which the clients can use to interact with the Service. The onRebind() function can be called after onUnbind(), if a new client connects to the Service.
Thats all for today. We will begin creating Services in the next part.
Thanks for reading!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.