Four major components of Android development: Service (detailed description) and four major components of android

Source: Internet
Author: User

Four major components of Android development: Service (detailed description) and four major components of android

Four components of Android development-Service

I. Service

Introduction

A Service is one of the four main components in the android system (Activity, Service, BroadcastReceiver, and ContentProvider). It is similar to the Activity level. The difference is that the Service can only run in the background without providing a user interface, and can interact with other components. A Service is an application component that can run on the background for a long time and does not provide a user interface. Another application component can start a service and will continue to run in the background even if the user switches to another application. In addition, a component can be bound to a service to interact with it, or even execute inter-process communication (IPC ). For example, a service can process network transactions, play music, execute file I/O, or interact with content providers in the background.

A service can basically have two forms:

Started:

A service is enabled. When an application component (such as an Activity) starts, it calls startService (). Once a service is started, it can run in the background indefinitely even if its components are destroyed. Generally, the service starts to execute an operation and does not return a result to the caller. For example, it may download or upload files over the network. When the operation is completed, the service should be destroyed automatically.

Bound:

A service is "Bound" when an application component is bound to it by calling bindService (). A binding Service provides a client-server interface that allows components to interact with the service, send requests, obtain results, and even perform inter-process communication (IPC ). One service can be bound to multiple customers at the same time. When multiple customers are unbound, the system will destroy the service.

Note:A service runs in its host process. The service does not create its own thread and does not run the main thread in a separate process (unless otherwise specified ). This means that if your service is intended to perform any time-consuming operations (such as MP3 playback or online downloads), you should create a new thread in the service to execute the job. By using a separate thread, you will reduce the number of non-response (ANR) errors of the application and the main UI thread of the application. You can continue to focus on responding to user operations.

2. Create a Service

To create a Service, you must create a subclass of the Service (or its existing subclass ). It processes some of the key callback methods of the Service life cycle in the implementation subclass, and provides a mechanism to bind components to the Service. You can rewrite these callback methods as needed:

OnStartCommand ()

Each time the client calls the startService () method to start the Service, the method is called back.

OnBind ()

This method is required by sub-classes of each Service. This method returns an IBinder object through which the application can communicate with the Service component. If you do not want to allow binding, null is returned.

OnCreate ()

This method will be called back immediately after the Service is created for the first time.

OnDestroy ()

When this method is called back before the Service is destroyed, the Service you created should clean out unused resources in this method, such as threads, registered listeners, and receivers.

Register the Service in the configuration file:

<Manifest...>
...
<Application...>
<Service android: name = ". ExampleService"/>
...
</Application>
</Manifest>

Iii. IntentService class

Because the first service does not need to process multiple requests at the same time (in fact, it is a dangerous multi-thread scenario), it may be the best if you implement your service using the intentservice class.

IntentService is a subclass of the Service class and is used to process asynchronous requests. The client can pass the request to the IntentService through the startService (Intent) method. In the onCreate () function, IntentService enables a thread to process all Intent request objects (sent by startService, this prevents transaction processing from blocking the main thread. After the work corresponding to the Intent request object is executed, if no new Intent request reaches, the Service is automatically stopped; otherwise, the task corresponding to the next Intent request is executed.

When processing transactions, IntentService still uses the Handler method to create an internal Handler named ServiceHandler and bind it directly to the subthread corresponding to HandlerThread. ServiceHandler encapsulates all the transactions corresponding to an intent into a virtual function called onHandleIntent. Therefore, we directly implement the virtual function onHandleIntent, you can perform different Transaction Processing Based on Intent.

In addition, IntentService implements the Onbind () method by default, and the return value is null.

Two steps are required to use IntentService:

1. Write Constructor

2. Implement the onHandleIntent virtual function and perform different Transaction Processing Based on the Intent.

Benefits: when processing asynchronous requests, you can reduce the workload of writing code and easily implement project requirements.

Note: The constructor of IntentService must be a constructor with an empty parameter, and then calls the constructor in the form of super ("name.

Because Service instantiation is completed by the system, and the system uses a constructor with null parameters to instantiate the Service.

The following is an instance of IntentService:

Public class HelloIntentService extends IntentService {

/**
* A constructor is required, and must call the super IntentService (String)
* Constructor with a name for the worker thread.
*/
Public HelloIntentService (){
Super ("HelloIntentService ");
}

/**
* The IntentService callthis method from the default workerthread
* The intent that started the service. When this method returns, IntentService
* Stops the service, as appropriate.
*/
@ Override
Protected void onHandleIntent (Intent intent ){
// Normally we wowould do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
Long endTime = System. currentTimeMillis () + 5*1000;
While (System. currentTimeMillis () <endTime ){
Synchronized (this ){
Try {
Wait (endTime-System. currentTimeMillis ());
} Catch (Exception e ){
}
}
}
}
}

4. The Lifecycle of a Service

Unlike the lifecycle callback function of an activity, you do not need to call the parent class to execute these callback methods.


Note:The left-side graph shows the service lifecycle created by StartService () and the right-side graph shows the service lifecycle created by StartService.

 

· The overall Service life time is fromOnCreate () isCall starts,OnDestroy ()Until the method is returned. Like Activity, the ServiceOnCreate ()InOnDestroy ()To release the remaining resources. For example, a music playback Service can create a music playing thread in onCreate () and stop this thread in onDestory.OnCreate ()AndOnDestroy ()Will be called by all services, whether the Service isStartService ()OrBindService ()Create.

· The active Service activity lifecycle (activelifetime) is fromOnStartCommand () or onBind ()Start with the call, and each of them processesStartService ()OrBindService ()Method passedIntentObject.

If the Service is enabled through startService (), its activity lifecycle ends with the entire lifecycle.

If the Service isBindService() Enabled. Their activity lifecycle ends after the onUnbind () method returns.

Note: although a Service is enabled by callingStopSelf ()OrStopService ()There is no corresponding callback function, that is, there is no onStop () callback method. Therefore, when the stop method is called, the system will directly destroy it unless the Service is bound to the customer component, and the onDestory () method will be called, this is the only callback method that will be called at this time.

5. Manage the Lifecycleof a Bound Service

After the binding Service is unbound from all clients, the Android system will destroy it (unless it isOnStartCommand ()Method ).

Therefore, if your Service is purely bound to a Service, you do not need to manage its lifecycle.

However, if you choose to implementOnStartCommand ()You must stop the service explicitly because the service is enabled at this time.

In this case, the Service always runs until it callsStopSelf ()Or call another component.StopService ()Whether or not it is bound to the client.

In addition, if your Service is enabled and bound, when the system calls yourOnUnbind ()If you want to acceptOnRebind ()(Instead of callingOnBind ()), You can chooseOnUnbind ()Returns true.OnRebind ()The return value is void, but the client is still in itsOnServiceConnected ()In the callback methodIBinderObject.

Shows the lifecycle of the Service (enabled and allowed to be bound:


To be continued .............


What are the four main components of Android? How do you understand them?

Android has four components: Activity, Service, Broadcast explorer, and Content Provider.

Activity

It is really difficult to build a complete Android program and don't want to use Activity, unless you want to be crazy. Because Activity is a window for interaction between Android apps and users, in my opinion, from this perspective, Android Activity is a webpage of a website.

Activity is undoubtedly the most complex among the four main components. During the past few years, a hook between something and the interface cannot be simplified. Think about it, you can figure out how much time it takes to create an independent application on the interface. In terms of visual effects, an Activity occupies the current window, responds to all window events, and has interface elements such as controls and menus. From the internal logic point of view, the Activity needs to do a lot of persistent things to maintain the status of each interface. It also needs to properly manage the lifecycle and some switch logic. For developers, they need to derive a subclass of the Activity, and then work hard to do the above. For more details about the Activity, see reference/android/app/Activity.html. In the future, we will provide a more detailed analysis.

Service

Service, in the most straightforward view, is to strip the Activity of the interface. They are very similar in many Android concepts and are encapsulated with a complete functional logic implementation, however, the Service is not exposed, but it is a solid backing silently.

But in fact, from another perspective, the services in Android are similar to the Windows Services and Web Background services that we usually call. These services are usually used for long running of the background and accept upper-layer commands, the module that completes related transactions. In running mode, Activity jumps from one to the other ..., this is a bit like a modal dialog box (or a web page ...), give an input (or no ...), then, regardless of whether you want it to run, the output (same as or without...) is returned when it leaves ...).

The Service is not, it is waiting, waiting for the upper layer to connect to it, and then generate a persistent and lingering communication, which is like an Ajax page, watching nothing changed, sneaky and Service, I don't know how many times it went.

However, unlike general services, the process model of Android services is configurable like all four components, both the caller and the producer can choose whether to run the component in the same process or in different processes. This sentence can be engraved into your mind, which highlights the running characteristics of Android. If a Service is expected to run in different processes of the caller, you need to use the RPC mechanism provided by Android to deploy a set of inter-process communication policies for it.

Shows the RPC implementation of Android, as shown in (well, it also comes from the SDK ...), nothing unusual. Based on an implementation of the proxy mode, a proxy class is generated on both the caller and the server side for serialization and deserialization, this allows both the caller and server to use the RPC interface just like calling a local interface.

The class used for data serialization in Android is Parcel. For details, see/reference/android/OS/Parcel.html. This class encapsulates the serialization details and provides an access interface that is sufficiently object-oriented, android is said to be very efficient.

There is also the Android Interface Definition Language (AIDL), an Interface-defined Language, and the RPC Interface of the service, which can be described by AIDL, the ADT can help you automatically generate a complete set of classes required for the proxy mode, which is the kind of kind that is hard to write. For more information, see guide & #47 ...... the remaining full text>

Functions of four android Components

Activity display interface (the displayed interface inherits the completion of the activity)
Service (running in the background, can be understood as an activity without Interface)
Broadcast Receiver er Broadcast (used for broadcasting and notification)
Content Provider Data Communication (communication between data, data between the same program, or communication between different programs)

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.