Android source code decoration mode --- ContextWrapper

Source: Internet
Author: User

Android source code decoration mode --- ContextWrapper

If the decoration mode application in the Android source code is the most obvious, it must be non-ContextWrapper, and ContextWrapper is a transparent and classic decoration mode. This article analyzes the Context source code structure through the decorator mode. The Android source code used in this article is (android 5.0.0 ). First, we will introduce the decoration mode.

Decorative Pattern intent

The decoration mode dynamically adds additional responsibilities to the object. In terms of adding functions, it is more flexible than the subclass method.

UML diagram

Simple code
Class Component {public void operate1 () {// do operate1 System. out. println ("operate1") ;}} class ComponentDecorator extends Component {private Component mComponent; public ComponentDecorator (Component component) {mComponent = component;} public void operate1 () {// Add related responsibilities System. out. println ("print before"); mComponent. operate1 () ;}} class ComponentChild {public void operate1 () {// do operate1 System. out. println ("child operate1") ;}} public static void main (String [] args) {ComponentChild component = new ComponentChild (); ComponentDecorator decorator = new ComponnentDecorator (component); decorator. operate1 ();}

The above Code simply implements the decoration mode. By using the decorated object as a member variable of the decoration device, when calling the operation of the decoration device, the decorator still calls the operation of the decorated object, but the decorator Can add related functions to the corresponding operation. The transparent implementation of the decorator is the same as that of the interface of the decorated object. No new interfaces are added, but more implementations are translucent. Compared with the sub-class implementation method, the decoration mode can decorate various sub-classes of the decorated objects, or even decorate the objects of the decorative decorations ), this is more flexible than adding sub-classes. If subclass is used, a large number of subclasses are generated.

ContextWrapper

The following describes how to use the decorator in the Android source code: ContextWrapper (the decorator has an alias Wrapper ). First look at the UML diagram.

Context

Context is a global application environment interface, which is implemented by the Android system. It can access application resources and start Activity and Service to receive broadcast.

It is an abstract class that contains declarations of various methods and should be viewed as an interface class.

ContextWrapper

This is a Context package, which contains an mBase, and ContextWrapper encapsulates the mBase. While

ContextThemeWrapper, Activity, Application, Service, ReceiverRestrictedContext

ContextThemeWrapper is a decoration device containing themes, and Activity is its subclass. Application, Service, and ReceiverRestrictedContext are subclasses of ContextWrapper. Each Application has an Application. Existing applications in Android Source Code include EmailApplication, LauncherApplication, and Browser.

ContextImpl

This is a class that truly implements Context. Context is an application environment class that contains various environment-related operations: getResource (resource management, including getAssets, layout, string, drawable, etc.), getPackageManager (packmanager), getContentResolver (used to obtain content models, such as Access ContentProvider), startActivity (start Activity), *** Service (including a series of Service-related operations, start, bind, unbind, stop), registerBroadcast/unregisterBroadcast/sendBroadcast (Broadcast-related)

The following describes how to implement these key methods.

GetResource

This is the interface for obtaining resources and obtaining Resource objects. ContextImpl contains a mResource member variable, which is read by mResource in android. MResource is generated by ResourceManager. Currently, many Android resources are dynamically loaded in the following way.

AssetManager assets = AssetManager. class. newInstance (); try {Method method = AssetManager. class. getMethod ("addAssetPath", String. class); method. invoke (assets, dexPath); // dexPath indicates the dynamic dex package path} catch (Exception e) {e. printStackTrace} r = new Resources (assets, getResources. getDisplayMetrics (), getResources. getConfiguration ());

However, the addAssetPath of assets is a hidden function that needs to be called through reflection.

In fact, the resource framework of Android is roughly as follows:
-Generate the corresponding ID based on layout, values, and drawable and save it under the R. id file, while the Android resources are in com. android. R. id. Assets are not assigned an id.
-Android uses different resource directory suffixes to adapt to different language Environments, screen size, such as drawable-en-w360. Android has a corresponding table, which is matched in sequence. For drawable, it matches the table based on the maximum value of the parameter of the corresponding mobile phone. Android will create an index based on these parameters during packaging.
-Package it into the resources. arsc file.

Application read process during running
-First drop the Resource Directory that does not match the mobile phone environment. For example, if it is a Chinese environment, remove the en directory.
-Assets are accessed by AssetsManager. Other resources are matched according to the order of the MMC table and one dimension of the index table, and filtered until the corresponding resources are found. If not found, an exception is thrown.

For more information about the above process, see Luo shengyang's blog.

GetPackageManager

Return to the Package Manager. The package manager can manage various information related to the application packages installed in the system. You can add permissions to view the package information of the corresponding package name, specify the component information of the component, and install the application package. The registration of different applications in Android is definitely different, and the package corresponds to the application. Therefore, to understand PackageManager, PackageManager is the manager for managing packages (application-level information processing.

GetContentResolver

Returns a ContentResolver. ContentResolver is used to obtain the Content model, and like ContentProvider, It is accessed through ContentResolver.

Activity operation

Context contains the startup operation of the Activity. The Startup Process of the Activity simply goes through the following steps:
1. mMainThread.instrumentation.exe cStartActivity
MMainThread is the ActivityThread type, which manages the execution of the main application thread, such as Activity scheduling and Broadcast. instrumentation is an Instrumentation type, which is the Android testing framework, this is to monitor the Activity. There is an ActivityMonitor to monitor the called Activity. You can also use ActivityMonitor to wait for a specified Activity to start. You can also stop an Activity from being started.
In this way, the Activity is started to monitor the Activity, which will be useful in testing. After startup, you can also check the component information returned after startup.
2. In the execStartActivity function, after monitoring, the specified Activity is started through ActivityManagerNative.

Int result = ActivityManagerNative. getDefault (). startActivity (whoThread, who. getBasePackageName (), intent, intent. resolveTypeIfNeeded (who. getContentResolver (), token, target! = Null? Target. mEmbeddedID: null, requestCode, 0, null, options); you can see that Native is actually accessed through an IPC Mechanism, specifically ActivityManagerProxy using Binder for IPC.
The Binder mechanism is used to access ActivityManagerService. ActivityManagerService is the core Service for Activity, Service, and Broadcast management. ActivityManagerService. startActivity Performs related processing through mStackSupervisor and ActivityStack, then goes through ApplicationThread, and finally starts ActivityService to the Handler (H) of the main thread.

In addition to startService, stopService, bindService, and unbindService. Services are managed in ActivityManagerService, but services are different. In ActivityManagerService, ActiveServices is managed. However, the process for controlling the Service will still reach Handler.

BroadCastReceiver

The Context contains sendBroadcast, registerReceiver, and unregisterReceiver. All corresponding functions of ActivityManagerService are called through ActivityManagerNative. BroadcastIntent processes sendBroadcast, and ActivityManagerService also has registerReceiver and unregisterReceiver. ActivityManagerService stores a Broadcast ReceiverList, which stores the Receiver during registration and finds the corresponding Receiver based on the saved IntentFilter when sending broadcasts. In addition, BroadCastReceiver also has sticky, yes. If the existing sticky broadcast is met during registration, it is immediately sent to the Receiver.

 
For the Activity and Service Startup Process, refer to Luo shengyang's blog. His blog is based on the early Android version. In fact, there are still many changes in many places. If you want to know the latest source code, you are advised to read the source code by referring to the blog. Next we will discuss the advantages of the Context in the decorative mode.

Benefits of ContextWrapper decoration Mode

I actually read the source code structure of Context and know that it uses the decoration mode. But why does this part use the decoration mode? Here, the decoration mode can well add responsibilities. For example, in the case of a consumer, ReceiverRestrictedContext can restrict the consumer to call startService, so that the consumer er of the application cannot start the Service. Through the implementation of the decorator, you can provide a variety of decorations, and also provide an application environment for Android Application Components.

Comparison with the inherited method for Adding Functions

We seem to be able to consider using inheritance to implement the Context structure. However, if we use inheritance to add functions to the Context, Application, ThemeContext, Service, and so on will be directly integrated from ContextImpl, if we need a new Context implementation method, it will become very troublesome. After the new ContextImpl is implemented, the Application has to inherit the new ContextImpl, on the other hand, subclass tree integration is very huge. Now we can replace the ContextWrapper decoration object directly in the decoration mode.

Rule Mode

Our Context needs to constantly add new responsibilities and decorations to the outside, while the policy mode replaces the system's interior. If we need multiple Context implementations, you can use the policy mode. Context is the Android application environment. In Android, the Android application environment is fixed. It will not change for different applications.

However, in other words, different implementations can be added to the decoration mode, and MockContext is also included in Android, but it is used for testing. This part can also be seen as a strategy, however, during normal operation, the main focus is on different decorations. This is actually the benefit of decoration.

Never frown, even when you are sad, because you don't know who will fall in love with your smile-"Birds set"

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.