Four major android components-Explanation of android service

Source: Internet
Author: User

1. Introduction to android service

1. Services in Android are similar to those in windows. services generally do not have user operation interfaces, and they are not easily noticed by users when running in the system, you can use it to develop programs such as monitoring.

2. In Android, Activity is mainly responsible for displaying front-end pages, and Service is mainly responsible for tasks that require long-term operation. For example, a music player playing music from the service should be set to run at the front end, because the user will pay attention to its operation. the notification in the status bar may display the current song and allow the user to start an activity to interact with the music player.

3. In our actual development, we often encounter communication between the Activity and the Service. We generally start the background Service in the Activity and start it through Intent, in Intent, we can pass data to the Service. What should we do if we want to update the UI thread after the Service executes some operations? Next, I will introduce two methods to implement communication between services and activities.

II. Implementation of Android Service
There are two types of services:
1. Start
Call the startService () method of an Application Component (such as Activity) to start a service. once started, the service will always run in the background, even if the application components are closed at this time. generally, a started service processes some single functions and does not need to return results to the caller. for example, download or upload a file on the network. the service is closed only when the service is finished.
2. Bound
BindService () method of the application component is called to bind a service. the Bound Service provides a client-server interaction interface. this interface is mainly used to interact with applications, send requests, obtain results, and even access processes through IPC. as long as a program component is bound to a service, the binding service will run. Multiple application components can be bound to a service at the same time. when all application components are unbound, the bound server is destroyed.
Next we will introduce "Started Service" and "Bound Servie" respectively.

3. Create and configure a service

1. To create a service, you must create a subclass of a Service class (or an existing subclass. in your implementation, you should overwrite some callback methods for handling key aspects of the service life cycle and provide a mechanism for binding components to the service (if needed ). the most important callback method you should override is:


OnStartCommand ()
The system calls this method when other components, such as activity, call startService () to request service startup. once this method is executed, the service starts and runs in the background for a long time. if you implement it, you need to stop the service when it completes the task by calling stopSelf () or stopService (). (If you only want to provide binding, you do not need to implement this method ).


OnBind ()
The system calls this method when the component calls bindService () and wants to bind it to the service (for example, to execute inter-process communication. in your implementation, you must provide an IBinder for the client to communicate with the service. You must always implement this method, but if you do not allow binding, then you should return null.


OnCreate ()
The system executes this method when the service is created for the first time to execute initialization only once (before calling the method such as onStartCommand () or onBind ). if the service is already running, this method will not be called.


OnDestroy ()
This method is called when the service is no longer in use and is to be destroyed. your service should release resources in this method, such as threads, registered listeners, and receivers. this is the last call received by the service.
If a component starts a service by calling startService (), the service will continue to run until it passes stopSelf () stop yourself or other components call stopService () to stop it.

If a component calls bindService () to create a service (onStartCommand () is not called), the service is only running during the binding period. once the service is unbound from all clients, the system will kill it.

2. Declare a service in manifest
Like activity and other components, you must declare all services in the manifest file of your application.
To declare your service, add The child of an element. For example:

 
      ...            
          
                                         
      
  
PS:

Like an activity, a service can define an intent filter so that other components can call themselves with a clear intent. by declaring the intent filter, components in any application on your device can start your sevice by passing matching intent to startService.
If you want to use your own service only in this application, you do not need to specify any intent filter. if you do not use the intent filter, you must use an intent that explicitly specifies the service class name to start your service.
3. Start a Service

The service cannot run on its own. You must call the Context. startService () or Context. bindService () method to start the service. Both methods can start the Service, but their usage is different.

The startService () method is used to enable the service. There is no relation between the visitor and the service. Even if the visitor exits, the Service continues to run.

The bindService () method is used to enable the Service. When a visitor is bound to the service, the service is terminated once the visitor exits. This feature features that the visitor does not want to live at the same time and must die at the same time.

Start the service using the Context. startService () method. You can only call the Context. stopService () method to end the service. The onDestroy () method is called when the service ends.

If the service does not provide the binding function, the intent sent to startService () is the only communication method between the application component and service. however, if you want the service to send a result back, the client that starts the service can create a PendingIntent for broadcast (using getBroadcast () and then transmit it to the service in the intent, then you can use broadcast to return the results.

PS: The difference between the two methods to start the service:

Start and close the service through startService () and stopService. It is applicable to the absence of interaction between services and visitors. If a method call or passing a parameter is required between the service and the visitor, use the bindService () and unbindService () Methods to start and close the service.

Use Context. the bindService () method starts the service. when the service is not created, the system first calls the onCreate () method of the service and then calls the onBind () method. At this time, the visitor and the service are bound together.

If the visitor wants to communicate with the service, the onBind () method must return the Ibinder object. If the visitor exits, the system first calls the onUnbind () method of the service and then calls the onDestroy () method. If the service has been bound before the bindService () method is called, multiple calls to the bindService () method will not result in multiple service creation and binding (that is, onCreate () and onBind () method is not called multiple times ). If a visitor wants to unbind from the service being bound, the unbindService () method can be called. Calling this method also causes the system to call the onUnbind () --> onDestroy () method of the service.

4. Stop a service

A "started" service must manage its own life cycle. this indicates that the system will not stop or destroy this service, unless the memory is insufficient and the service continues to run after onStartCommand () returns. therefore, the service must call stopSelf () to stop itself or use another component to call stopService () to stop it.

Once a stop request is sent through stopSelf () or stopService (), the system will destroy the service as soon as possible.

However, when using both startService and bindService, you must note that the termination of the Service requires both unbindService and stopService to terminate the Service, regardless of the Call Sequence of startService and bindService, if the unbindService is called first, the service will not be automatically terminated at this time, and then the service will be stopped after the stopService is called. If the stopService is called first, the service will not be terminated at this time, the Service stops automatically after unbindService is called or the Context of bindService is called does not exist (for example, when the Activity is finished;

Note: It is very important for your application to stop all its services after it completes its work. this avoids wasting system resources and consuming power. if necessary, other components can call stopService () to stop the service. even if you enable binding for the service, you must stop the service yourself, even if it receives a call to onStartCommand.


Iv. Service lifecycle callback Method

The service life cycle is related to the method used to start the service:
1. When the Context. startService () method is used to start the service, the related lifecycle Method
OnCreate () --> onStart () --> onDestroy ()
OnCreate () This method is called when a service is created. This method is called only once. No matter how many times the startService () or bindService () method is called, the service is created only once.
OnStart () calls back this method only when the Context. startService () method is used to start the service. This method is called when the service starts running. Although the startService () method is called multiple times, the onStart () method is called multiple times.
OnDestroy () is called when the service is terminated.

2. When the Context. bindService () method is used to start the service, the related lifecycle Method
OnCreate () --> onBind () --> onUnbind () --> onDestroy ()
OnBind () calls back this method only when the Context. bindService () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the Context. bindService () method will not cause this method to be called multiple times.
OnUnbind () calls back this method only when the Context. bindService () method is used to start the service. This method is called when the caller and the service are unbound.

If you use the startService () method to start the service, then call the bindService () method to bind to the service, then call the unbindService () method to unbind, and finally call the bindService () method to bind to the service again, the method for triggering the lifecycle is as follows:
OnCreate () --> onStart () --> onBind () --> onUnbind () [true must be returned for the overloaded Method --> onRebind ()

The following flowchart illustrates the lifecycle of the "startService ()" and "bindService ()" methods.



PS:

The life cycle of a service is much simpler than that of an activity. however, you still need to pay close attention to how your service is created and destroyed, because a service can run in the background and users cannot see it.
The life cycle of the service-from when it is created to when it is destroyed-there are two ways to go:

A "started" service
When other components call startService (), create. Then the service runs for a long time and must call stopSelf () to stop itself. Another component can also call? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> memory + 1zbO + zc/6u9nL/KOuPGJyPgo8YnI + Memory + KNK7uPa/Upper/lower/a0 + upper/Nu6e2y7/lower NlsqLH0rWxy/merge + jrtauuvOjrLWx08O7p8/rttSypbfFxve9 + NDQ0rvQqbLZ1/e78t Kqu/samples + samples/samples + m/9 s/samples/bfHy/samples/7sPO2qMHLo648YnI + c1_vcd4kpha + PGJyPgo8L3A + CjxwPjxzdHJvbmc + samples Examples/zTptPD1 + m8/samples + sPO2qLW9y/zKsbLFu + 7 XxaOsy/nS1LWxw7vT0NfpvP6w87aotb3L/Mqxo6zPtc2zvs274WtpbGzL/Samples Examples/examples + CjOhorbguPa/zbuntsu/examples/zbuntsvN6rPJ0 + tzZXJ2aWNltcS9u7ulo6zL/LX308N1bmJpbmRTZXJ2aWNlKCnAtL 3is/latest + 1zbO + latest/latest + latest 70Km/latest/T0NK 70Km/zbuntsu/ydLUtffTw7XEuau/qre9t6ijrjrjxicj4kpgjypg Examples/zbuntsu/examples + examples/aOuPGJyPgo8YnI + examples + c?vcd4kpha + PGJyPgo8L3A + CjxwPsD9yOejus/Cw + bV4rj2c2VydmljZczhuanIw7/Nu6 Attributes = "brush: java;"> public class LocalService extends Service {// Binder given to clients private final IBinder mBinder = new LocalBinder (); // Random number generator private final Random mGenerator = new Random ();/*** a Binder class is defined here and used in onBind () methods, in this way, the Activity side can obtain * in the Local Service, we directly inherit the Binder instead of IBinder, because B Inder implements the IBinder interface, so we can do less work. */Public class LocalBinder extends Binder {LocalService getService () {// return the instance of this service to the client, so the client can call the public method return LocalService of this service. this ;}@ Override public IBinder onBind (Intent intent) {return mBinder;}/** method to be called by the client */public int getRandomNumber () {return mGenerator. nextInt (100 );}}The following is an example of actvity that is bound to LocalService and called getRandomNumber () when the button is pressed:

Public class BindingActivity extends Activity {LocalService mService; boolean mBound = false; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main) ;}@ Override protected void onStart () {super. onStart (); // Intent intent = new Intent (this, LocalService. class); bindService (intent, mConnection, Context. BIND_AUTO_CREATE) ;}@ Override protected void onStop () {super. onStop (); // unbind from service if (mBound) {unbindService (mConnection); mBound = false ;}} /** call when the button is pressed (the button defined in the layout file uses the android: onClick attribute to specify the response to this method) */public void onButtonClick (View v) {if (mBound) {// call a method of LocalService // However, if there is a pending operation in this call, this request should be sent // generated in another thread to Avoid Lowering the activity performance. int num = mService. getRandomNumber (); Toast. makeText (this, "number:" + num, Toast. LENGTH_SHORT ). show () ;}}/** defines the callback bound to the service and transmits it to */private ServiceConnection mConnection = new ServiceConnection () {@ Override public void onServiceConnected (ComponentName className, IBinder service) {// we have already bound the service to LocalService. We can forcibly convert the IBinder type and obtain the LocalService instance. localBinder binder = (LocalBinder) service; mService = binder. getService (); mBound = true ;}@ Override public void onServiceDisconnected (ComponentName arg0) {mBound = false ;}};}
The preceding example shows how the client binds an instance of ServiceConnection to the service using the onServiceConnected () method.

PS:

1. The application component (client) can call bindService () to bind to a service. Android system and call the onBind () method of the service. It returns an IBinder used to interact with the service.

2. Binding is asynchronous. bindService () will return immediately, and it will not return IBinder to the client. to receive IBinder, the client must create a ServiceConnection instance and send it to bindService (). serviceConnection contains a callback method. The system calls this method to pass the IBinder to be returned.

3. Bind your client to a service. You must:

1) Implement ServiceConnection.
Your implementation must rewrite two callback methods:
OnServiceConnected ()
The system calls this to send the IBinder returned in the onBind () of the service.
OnServiceDisconnected ()
Android calls this method when the connection to the same service is accidentally lost. For example, when the service crashes or is forced to kill, this method will not be called when the client unbinds.
2) Call bindService () and pass it to the ServiceConnection implementation.
3) when the system calls your onServiceConnected () method, you can use the methods defined by the interface to call the service.
4) to disconnect from the service, call unbindService ().
When your client is destroyed, it will be unbound from the service, however, you must always unbind the service when you complete the interaction with the service or when your activity is paused, so the service can be disabled when it is not in use. (we will discuss more about binding and unbinding when appropriate.

4. With this ServiceConnection, the client can bind it to a service and pass it to bindService (). For example:

Intentintent = new Intent (this, LocalService. class );
BindService (intent, mConnection, Context. BIND_AUTO_CREATE );

The first bindService () parameter is an Intent that explicitly specifies the service to be bound.

The second parameter is the ServiceConnection object.

The third parameter is a flag indicating the operation in the binding. it should generally be BIND_AUTO_CREATE, so that a will be created when the service does not exist. other optional values are BIND_DEBUG_UNBIND and BIND_NOT_FOREGROUND. If you do not want to set the value to 0.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.