Android Component Model Resolution "Essentials Notes for Android development"

Source: Internet
Author: User
Tags message queue

Android component model to resolve mashups in Android

The application is divided into different categories of components, through a unified positioning model and interface standards to integrate them together to complete a task.
In Android's mashup mode, the functionality of each component can be fully reused. Components from different applications can be combined organically to accomplish tasks together.

A mashup-based Android application model

Three basic elements: component, connection, configuration

An interface is an implementation unit.
In code, a component is an implementation derived from a subclass of a particular interface or base class, such as an interface component activity that refers to a subclass implementation derived from the Android.app.Activity class.

A connection is a communication channel between a component and a component, which is a pattern of calls and communication presets between Android for different categories of components. For example, the communication connection with the interface components, through the intent object to establish, and the data Source component communication, then through the URI address to locate and build the connection path

Configuration is information used to describe the functionality and implementation characteristics of a component.
The component Management Service for Android is to understand the characteristics of each component through the information in the configuration file.

To send a message as an example

Mashup-based application architecture features

The core is the component, in Android, the aggregation unit at the time of component execution is a task, each task consists of several interface component objects, which can come from different applications, run in different processes, and are independent of each other, without concern for the implementation details of the specific caller or callee.
The data transmission between components is carried out by means of serialized data transmission such as message, interprocess communication model, and not by direct transfer of object pointer, which makes Android's application inherently have good cross-process characteristics.

Interface Component Activity parsing

The Android interface component does not follow the MVC architecture, and its design understanding is closer to the Web page. After all, the idea of architecture for Android applications stems from the concept of mashups in Web2.0.

    • From the operating mode, Android is a multi-tasking operating system, you can run multiple tasks at the same time, each task has an interface component stack, the elements of the stack is an instance of the interface Component object, which is responsible for interacting with the user is the front desk task stack top component.
    • Android interface components are used to locate information such as type information, data URI information, data type information, and so on. The switching and data transmission of interface components depend on the unified scheduling and delivery of Android component management services.
    • The functionality of the Android interface component is similar to that of a Web page, and is analogous to a functional black box. In web development, some state information is stored through cooik, and for the same design consideration, there is an application Environment object (application context) for each application process of Android, and the shared data of small amount of data can be stored by it.

The "Process construction interface" uses the Setcontentview () method with the help of the R class.
The "Process interaction Events" category is the global event at the current interface, which can be implemented by overloading specific methods in activity, and the interaction time associated with a specific control, and the Android control uses the observer pattern to handle related events by adding listeners.
"Managing Data for Interface components" Android is a multitasking operating system, and when too many tasks are running, it is necessary to automatically end some applications and components to ensure that the system has sufficient memory space to perform new tasks. Android takes a process-managed policy. For the developer, it is necessary to properly maintain the relevant state according to the life cycle model of the interface component, to serialize and save the relevant information when the component is destroyed, and to accurately revert to the state before the destruction when the application is reconstructed to ensure the consistency of the user experience.
The task model for configuring interface components The Android interface component is organized by tasks at run time. The interface components in the same task are arranged linearly according to the stack model. For example, when a program component needs a lot of resources, there should not be too many instances in the characters at the same time, but it is more likely to be reused to reduce the overhead of the system. To do this, Android provides a variety of component task models to adjust the order of elements in the stack, or to split a single task into multiple tasks, or even to put the task into a different process to improve execution efficiency, through Launchmode in the configuration file, Cleartaskonlaunch, Process parameters, and when using other interface components, you also need to control the task model of the target component through the intent flag bit (flags).
"Adapting to environment configuration changes" Many of the configuration information changes depending on device and environment factors, such as hard keyboard disappearance, screen orientation, language environment, etc. When configuration information changes, the interface components that are interacting with the user need to adapt to these changes in a timely manner to provide the most appropriate interaction for the user. By default, when configuration information changes, Android simply destroys the interface component object that is currently interacting and re-constructs the Component object based on the new configuration information. If the component is not expected to be destroyed with a configuration information, it can be identified by the activity configuration item configchanges. And to handle the change events of the related configuration more finely in the activity.onconfigurationchanged function.

Data structure of interface components


Activity derives from the context class, which provides a basic environment for the application to run, and a bridge between the components and the system service communication.
The context class is an abstract class, and the Contextimpl derivation implements its abstract interface.
The Contextimpl object establishes a remote connection to the various services of the Android framework layer, communicating through the communication mechanism (IPC) between the Andorid processes and the services.
The abstraction and encapsulation of the context hides the details of the application's communication with the system service, simplifying the development of upper-level applications. Contextimpl is instantiated when the Android component Management Service constructs individual component objects.
Contextwrapper's design applies a cosmetic pattern, which derives from the context, where the implementation is accomplished by invoking the instance of Contextimpl in a combined manner. Such a design allows the implementation of Contextimpl and Contextwrapper subclasses to vary independently from one another.
Android Interface components activity, service Component Services, and application base class application are all derived from contentwrapper, and they can be overloaded to modify the implementation of the context interface

Serviced Component Service resolution

Android's service components derive from the service class,
From the operating mode, the Android service component is not running in a separate process or thread. By default, the service component is constructed in the application process and, like all other Android components, runs in the main thread of the process (that is, the UI thread). This means that if the time-consuming operation is performed synchronously in the serviced component, it can cause the main thread to block or the interface to suspend animation, thus unable to respond to the user's actions. From the view of usage, the service component can establish two-way connection with the front-end interface components, provide data and function support, and can accept the request of intent object in one way, analyze processing and function dispatch of the data.

Features and characteristics of serviced components

Take the alarm clock as an example:

In this mode, the service component plays a role as a function dispatcher. Collect various event information from the event trigger object, further analyze and process it, then update the interface, modify the data, or make other related presence, dispatch the entire application to keep it in the correct state.
A service component can also play another very important role, the interface component of the feature provider. In some scenarios, you should be able to stay in your own interactive interface and communicate with users. At this point it does not need to re-use the third-party interface, but only need to obtain some functionality and state data, such support is provided through the service components.
The Input method framework is an example of reuse based on a service component.


The input interface component initiates a connection request by calling the Bindservice function. The Onbind method of the Input Method service (Inputmethodservice) is called and constructs an IBinder object to be returned to the Input method interface component, which establishes an IPC connection, which can be used by the remote method call to perform input-related operations, and after the service is terminated. The Unbindservice function should be defined to terminate the connection.

Development and use of service components

Constructs a subclass of the service, registering it in the configuration file.
The function to construct a service component that plays the role of dispatcher is Onstartcommand, and it is important to note that in Android all components are constructed on the main thread, so the execution of the Onstartcommand function blocks the main thread. If it involves time-consuming operations such as database reading and writing, network communication, and complex operations, then it is necessary to put the relevant operations into a separate process or thread to execute.
The component is placed in a separate process and can be implemented through the process parameters of the configuration file.
But this approach increases the overhead of the process, and another viable strategy is to have a separate thread in the serviced component, handing over time-consuming and laborious operations to him.
The simplest implementation strategy is to execute the processing logic in the serviced component by deriving Intentservice.

Private Final class Servicehandler extends Handler {public Servicehandler (Looper Looper) {super (Looper        );            } @Override public void Handlemessage (Message msg) {onhandleintent ((Intent) msg.obj);        Stopself (MSG.ARG1); }    }
public void OnCreate () {//Todo:it would is nice to a partial wakelock//during PR  Ocessing, and to has a static StartService (Context, Intent)//method that would launch the service & hand off        A wakelock.        Super.oncreate ();        Handlerthread thread = new Handlerthread ("intentservice[" + Mname + "]");        Thread.Start ();        Mservicelooper = Thread.getlooper ();    Mservicehandler = new Servicehandler (mservicelooper); }

Intentservice implementation principle: itself is a subclass of service, when started, will be in the OnCreate function to establish a background thread, the thread through its independent message loop in the background waiting for events, When the Onstartcommand function is connected to the relevant intent parameter, the main thread will package its contents into a background process and process it in the Onhandleintent function, from the implementation point of view, Just move the logical content that should be placed in the Onstartcommand to Onhandleintent. If the Bindservice function is used to bind the service component to establish a connection, then the Onbind function is processed, and the Onbind function receives the intent object emitted through the Bindservice function, depending on the intent object, The Service.onbind function returns the corresponding IBinder object, and the entire binding process is an asynchronous operation in which the component Management Service participates in scheduling. The IBinder object returned by the Onbind function is passed to the caller by invoking the Onserviceconnected method of the Serviceconnection object, which, after the caller gets the IBinder object, can be called by the remote method with the serviced component process.
When you do not need to communicate with the serviced component, call the Unbindservice method to close the connection.

interprocess communication model for serviced components

In real-world applications, foreground interface components and background service components may come from different applications, which requires interprocess communication. The Android inter-process communication model consists of three main areas:
"Android Inter-process communication model Architecture" typical proxy pattern

In a proxy object, each function interface has a corresponding instruction value. When the caller invokes this interface, proxy serializes the data and instructions into a message that is sent to the stub object at the far end. The stub object will disassemble the corresponding instruction and data, execute the corresponding logic according to the instruction, and return the result to the interface caller, the whole process is completely transparent to the caller.
The occurrence and return of proxy packets is done by binder. In the Binder object, there is a background message loop thread, the message packet from the proxy will be thrown into the message queue waiting for parsing and processing, stub objects are the binder of the sub-type, the server is instantiated, its interface and implementation of the proxy one by one match, is responsible for the message passed through the proxy to unpack, get the instructions and data. In practical applications. Each stub will have an implementation subclass implement, which is actually responsible for executing the called function in the binder's background thread.
The interface component can obtain IBinder object through Bindservice, and through its static method Asinterface can obtain the proxy object instance. By using the proxy object at the interface end, remote invocation of the service-side function can be implemented.
The call to the IPC method is a synchronous process that, if it takes too long to execute, blocks the caller's thread, requiring an asynchronous IPC call.

Constructs an asynchronous IPC method call that needs to pass in another IInterface object whose Stub object (callback.stub in the diagram) is calling the component, and its Porxy object (Callback.proxy in the diagram) is transferred to the serviced component as it is serialized. A callback notification for the service side after the operation has completed. After the service component finishes operation, the role-playing caller is converted and the execution result is notified to the calling component through the methods in the Callback.proxy object.

"framework code auto-generation" There are fixed types and methods in the entire process communication model that need to be implemented, including many trivial and similar serialization and deserialization operations. With the help of Aidl (Android INTERFACR deifinition Language) The
AIDL is an interface description language, the syntax is derived from Java, The control of the input and output direction is added to the parameter. The Android SDK provides a Aidl parsing tool that automatically generates the corresponding MY_API, MY_API, based on the Aidl file provided. Proxy, My_api. Java files of the stub type. Developers only need basic MY_API. Stub, implement the implement type, populate the real execution code without needing to focus on the other underlying communication details.
"parameter serialization" throughout the process of interprocess communication, an important step in the process of passing data from one process to another is the serialization and deserialization of data-the basis for all interprocess communication.
There are three main types of data that are supported by

    • Basic data and their lists, array objects.
    • A subtype object that implements the Parcelable interface-a subtype that implements serialization-related operations by deriving the Writetoparcel method and providing a constructor function.
    • Subtype objects of IBinder and IInterface can also be serialized by parcel.

Parcel the serialized data is a binary stream of the homogeneous bits.
Inter-process communication mechanism is an important foundation of Android, the implementation of parcel type is mainly implemented by C + +, the upper parcel object is called through the JNI interface, which improves the execution efficiency of the serialization related operation and ensures the Android system can run efficiently.

The Context.getsystemservice interface to obtain the specified system services, which are not implemented by service components, are located in the core process of the system and have separate thread space.
What is obtained through Context.getsystemservice is actually the proxy object of these services, which establish a connection with the real service thread and implement the corresponding method through the IPC call.

Trigger Component Broadcast receiver parsing

The so-called trigger component, which is derived from the Broadcastreceiver subtype. Its implementation is concentrated in the OnReceive method.

Features and characteristics of the trigger component

When using a trigger component, it can only be used as a function, except for some of the member variables that are passed in when the constructor is initialized, and the rest is useless and will not be used. The execution of the function OnReceive must be synchronous and fast, otherwise it will block the current process interacting with the user.

Common trigger component usage patterns

The design of the trigger component solves the background event monitoring problem. In Android, the component Management Service constructs the process of executing components only when the event actually occurs, based on the configuration information that informs the corresponding trigger Component object.

Use of Trigger components

There are two methods for time monitoring using the trigger component, namely cold-Plug and hot-plug.

    • Cold unplug is to write information about the trigger component in the application's configuration file.
    • Hot-swappable, through Registerreceiver and Unregisterreceiver, dynamically binds the trigger component to the time it needs to be monitored. In actual development, the trigger component is usually registered in the activity's Onresume function, and the corresponding trigger component is unregistered in the OnPause function.
Sending of broadcast events

Broadcast events are represented by intent objects and broadcast events need to be sent via sendbroadcast or Sendorderedbroadcast functions

With Sendbroadcast's normal broadcast mode, this mode, all the trigger components registered for the broadcast event are notified of the event and executed concurrently in the respective application process.

Through Sendorderedbroadcast's ordered broadcast mode, all the trigger components that listen to the event are sorted according to the prioritized priority, processing the event from high to low. A high-priority trigger component can first terminate the propagation of this broadcast through the Abortbroadcast method, so that the low-priority trigger component no longer has the opportunity to handle the event. During the delivery of an ordered broadcast event, each executing trigger component can append additional data to the event message through functions such as Setresult, and the next trigger component that handles the event can use the data. In this way, event broadcasts form a chain of message data processing, in order to ensure that the event is bound to be processed, the sender of the broadcast event can also indicate the default trigger component, and if the propagation of the event is not prematurely terminated, the trigger component responds to the event at the end.

Data Source component Content provider parsing

Unlike other components, the data source component does not contain specific functional logic, but rather is the interface that provides data access to the application.

Positioning and manipulation of data source components

uri, the global unified positioning flag, through a structured string, uniquely flag the address information of the data source. The network address URL, which is a subclass in which each data source component has a unique URI identifier

 
" Style= "border:0px; Display:block;font-family:consolas, Inconsolata, Courier, monospace; Font-weight:bold; White-space:pre; margin:0px;border-top-left-radius:3px; border-top-right-radius:3px; border-bottom-right-radius:3px; border-bottom-left-radius:3px; Word-wrap:break-word; border:1px solid #cccccc; padding:0px 5px; margin:0px 2px;font-size:1em; Letter-spacing: -1px; Font-weight:bold; " ><provider android:name= "Simplecontentprovider" android:authorities= "Com.duguhome.prodiver.sample" ></ Provider>

The naming of a data source component URI typically requires that it be associated with the package name of the application to ensure uniqueness on the same Android device. If you discover that a data source component with the same URI address already exists on your device when you install the app, the new app will fail to install due to conflicting data source components.

The data source component can also define operations in the rest way.

# Operation content://com.duguhome.provider.sample/items# the entry with ID 1 for the list type operation Content://com.duguhome.provider.sample/items /1  

Rest is designed based on the HTTP protocol.
To increase control of the data, Android also introduces support for SQL statements for the data source component.

Development of data Source components

Derive from the ContentProvider class and implement an abstract method that requires information such as its URI in the configuration file.
Reading and writing data directly to a data source component may block the main thread, affecting the interaction applied to the user. When a large number of reads and writes and queries are involved, callers can implement asynchronous access to the data source component through the Asyncqueryhandler object. Each Asyncqueryhandler object opens a background thread that interacts with data source components in the thread to perform data additions and deletions.

Token helps the caller determine the request

Implementation details for the data source component

Contentresolver is the same as the DNS and local proxy of the data source component, which is responsible for locating each URI to the specific data source component, and through it to the data source for the operation of the additional pruning and checking.
Contentresolver the operation of the data, in fact, is completed in two steps, the first is the location, according to the URI to find the corresponding data source component, and then the corresponding data source component to perform the requested operation.

There is a data source component for the cache object Providermap, which stores each URI corresponding to the data source Component object.

The Contentresolver cached data Source Component object is actually a proxy for the data source component. When Contentresolver invokes its interface for operation, the relevant instructions are packaged into messages, passed through the Android interprocess communication mechanism to the remote data source component, and the data source component executes and then the result is serialized back, the entire process is a synchronous operation.

By default, each data source component has only one instance, and the requirements from different processes interact with each other through interprocess communication mechanisms, and if frequent interactions are expensive, you can configure the parameter mutiprocess to True, at which point, The data source component constructs a Component object in each application process that invokes it, avoiding the overhead of interprocess communication, thus improving the efficiency of operations and data transfer

When querying a data source process, the data needs to be copied from the process in which the data source component resides in the process where the caller resides.
Disposable copies waste time, waste memory, and each time you copy a cost that increases inter-process communication. Android uses the Data window mode. In the cursor of the data pointer object, contains a Cursorwindow object that caches part of the data at the caller's end, with the contents of the cached data containing several pieces of data related to the position of the current pointer. The underlying implementation of the Cursorwindow class is based on C + +

Application Profile Resolution

Permissions Configuration

 " Style= "border:0px; Display:block;font-family:consolas, Inconsolata, Courier, monospace; Font-weight:bold; White-space:pre; margin:0px;border-top-left-radius:3px; border-top-right-radius:3px; border-bottom-right-radius:3px; border-bottom-left-radius:3px; Word-wrap:break-word; border:1px solid #cccccc; padding:0px 5px; margin:0px 2px;font-size:1em; Letter-spacing: -1px; Font-weight:bold; " > < permission Android:name= "android:label=" Permission's name "android:description=" Permission specific description "Android:permissio ngroup= "Android.permission-group.cost_money" android:protectionlevel= "normal"; 

The defined permissions also need to be deployed to the corresponding components to take effect, and when the component Management Service constructs a Component object, it verifies that the permission claims of the requesting component match the permissions configuration of the component (if the request component and the implementing component are in the same application, without checking), and throws an exception to prevent this call if the match fails. Android's permission system is not transitive.

Permissions can also be called checkpermission function dynamic checksum at run time, without prior deployment on the component.

Android Component Model Resolution "Essentials Notes for Android development"

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.