Android Source Adapter Mode---activity class structure

Source: Internet
Author: User

In fact, the adapter mode in the Android source code is very much, and from the overall source angle to see the structure of activity is an adapter mode. Looking at activity from this perspective, there is a deeper understanding of activity and the application Layer framework.

Adapter Mode Intent

Converting an interface to another interface required by the user, the adapter mode makes it possible for those classes that would otherwise not work together because of incompatible interfaces.

UML diagram

There are two modes of adapter mode, the UML is as follows:

The first is to directly inherit an existing interface to adapt the target interface, and the second is to refer to an existing interface to adapt the target interface.

Sample code
 interface Target{    voidRequest ();} class adaptee{     Public voidSpecialrequest () {System.out.println ("Special from Adaptee"); }} class Adapter extends adaptee implements Target{     Public voidRequest () {//do something to implements requestSpecialrequest (); }} Public Static Final voidMain (String args[]) {Target target =NewAdapter (); Target.request ();}

The above is a simple code example of the first adapter pattern, which is adapted by inheriting existing classes, and the other is in the following way:

 interface Target{    voidRequest ();} class adaptee{     Public voidSpecialrequest () {System.out.println ("Special from Adaptee"); }} class Adapter implements Target{    PrivateAdaptee adaptee; Public voidAdapter (Adaptee adaptee) { This. adaptee = Adaptee; } Public voidRequest () {//do something to implements requestAdaptee.specialrequest (); }} Public Static Final voidMain (String args[]) {Target target =NewAdapter (NewAdaptee ()); Target.request ();}

There are two ways of class adapters and object adapters.

Activity and Adapter mode

Activity is the core component of Android, which is the component responsible for applying the UI, which is the most important, most used, and most complex form of Android's four components. Its source code is also quite large. From the adapter point of view, the activity is adaptable to multiple interfaces, first look at its class structure diagram:

Looking at activity as an adapter mode may be a bit farfetched at first. But Contextthemewrapper is the environment class that represents the theme, the context can be translated into the application environment, but for an application that needs to display the UI in addition to the application environment, but also need to adapt to other content information, such as window, such as KeyEvent and so on.

Take the window System for example. There is a window management system in Android, but the Windows system needs to be with the Window.callback interface, but now there is a context, the build needs to Window.callback interface, so create activity (this is adapter) Implement the Window.callback interface, and inherit the Contextthemewrapper, and Contextwrapper and window.callback work together to get the context working with the window. Window.callback is just one of the interfaces for activity adaptation, each of which describes each part of a class structure.

Contextthemewrapper

This is a theme of the context decorator, itself contextwrapper is an adorner mode, in Android, the four major groups are Contextwrapper sub-class, the four major formation need to apply the environment. About this section can see me this article Android source decoration mode-contextwrapper. It is necessary to understand that the context is a type of application environment, which contains various information related to the application environment and can be used to deal with the application system.

Window.callback, Window.onwindowdismissedcallback

Window.callback This interface contains a number of interface functions, the above UML diagram contains only a subset of interfaces, all of the interface classes can be seen below the outline:

This interface is the callback interface of the window, mainly divided into screen event trigger, key event trigger, panel related view creation and Prepare,menu Callback, window change callback, SearchRequest callback, and Actionmode callback.

Window.onwindowdismissedcallback is a hide class, which cannot be called through the API, but is the callback interface when the window disappears (when the Windows system is removed). The implementation of the activity is also very simple, directly finish off their own.

/** * Called when the main window associated with the activity has been dismissed. * @hide */@OverridepublicvoidonWindowDismissed() {    finish();}

Callback,onwindowdismissedcallback is the callback interface that window interacts with the activity.

The initial part of the code is:

//activity.javaFinalvoidAttach (context context, Activitythread Athread, Instrumentation instr, IBinder token, int ident, APP Lication application, Intent Intent, activityinfo info, charsequence title, Activity parent,StringID, nonconfigurationinstances lastnonconfigurationinstances, Configuration config,StringReferrer, Ivoiceinteractor voiceinteractor) {attachbasecontext (context); Mfragments.attachhost (NULL /*parent*/); Mwindow =NewPhonewindow ( This); Mwindow.setcallback ( This); Mwindow.setonwindowdismissedcallback ( This); Mwindow.getlayoutinflater (). Setprivatefactory ( This); ...

But in fact a window is not only associated with an activity, but a window and a callback association, activity is also context,android in dialog contains window, The dialog also implements the callback interface. An application environment (context) may contain multiple windows, there will be multiple callback, but the activity of the application environment itself to implement the callback interface.

Keyevent.callback

Corresponding to the callback interface of the key event, the interface is recalled when the key is pressed. The main purpose is to adapt the input system.

ComponentCallbacks2

It is a sub-interface of Componentcallbacks and Compoentcallbacks contains the following two interfaces:

void onConfigurationChanged(Configuration newConfig);void onLowMemory();

ComponentCallbacks2 added an onTrimMemory interface.
Componentcallbacks is a callback interface specifically for Android components that are implemented by Android components (now CONPONENTCALLBACKS2), which are called when configuration information changes and memory changes. These interfaces are called Activitythread (in the message loop, when the change message is received), Viewrootimpl (Viewrootimpl is responsible for communicating with Windowmanagerservice when the window changes), and so on. This interface is designed to fit the information management part of a system.

Here are two memory-related interfaces, in fact, to help the app deal with the full load of Android memory, remind the application to do some free memory processing, if the memory is too large, the application will be more likely to be killed. Specific can see Lowmemorykiller introduction.

Oncreatecontextmenulistener

Android context Menu: When a context menu is registered for a view, the view is long pressed for 2 seconds and a floating menu pops up. Oncreatecontextmenulistener it has only one interface function:

publicvoidonCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {    }

When the context menu of the view is created, the interface is invoked to get the menu (the menu is set as the activity that implements the interface modification). In activity, the function corresponding to this interface function is oncontextitemselected, and the function is a onmenuitemselected function that inherits from the Window.callback interface:

     Public Boolean onmenuitemselected(intFeatureid, MenuItem Item) {Charsequence titlecondensed = item.gettitlecondensed ();Switch(Featureid) { CaseWindow.feature_options_panel:if(titlecondensed! =NULL) {Eventlog.writeevent (50000,0, titlecondensed.tostring ()); }if(onoptionsitemselected (item)) {return true; }            ... CaseWindow.feature_context_menu:if(titlecondensed! =NULL) {Eventlog.writeevent (50000,1, titlecondensed.tostring ()); }if(oncontextitemselected (item)) {//Here                    return true; }returnmfragments.dispatchcontextitemselected (item);default:return false; }    }

We normally listen to the normal menu function onOptionsItemSelected is also onMenuItemSelected called by.

In the other side of view, the function that shows ContextMenu is showcontextmenu:

publicbooleanshowContextMenu() {    return getParent().showContextMenuForChild(this);}

The Showcontextmenuforchild of ViewGroup is:

publicbooleanshowContextMenuForChild(View originalView) {    returnnull && mParent.showContextMenuForChild(originalView);}

getParent()The ContextMenu will eventually be created in the Decorview,decorview. Then call the view createContextMenu method and end up using Moncreatecontextmenulistener to get the menu:

 Public void Createcontextmenu(ContextMenu menu) {Contextmenuinfo menuinfo = Getcontextmenuinfo ();//Sets the current menu info so all items added to menu would have    //My extra info set.((menubuilder) menu). Setcurrentmenuinfo (Menuinfo);    Oncreatecontextmenu (menu); Listenerinfo li = mlistenerinfo;if(Li! =NULL&& Li.moncreatecontextmenulistener! =NULL) {Li.mOnCreateContextMenuListener.onCreateContextMenu (menu, This, Menuinfo); }//Clear The extra information so subsequent items that aren ' t mine don ' t    //Have my extra info.((menubuilder) menu). Setcurrentmenuinfo (NULL);if(Mparent! =NULL) {Mparent.createcontextmenu (menu); }}

Decorview in Phonewindow, the menu is actually managed by window, the interface that responds to the Click event of item is consistent ( Window.Callback.onMenuItemSelected ), and the ContextMenu actually shows a dialog. But since ContextMenu is the same as the view, with the Oncreatecontextmenulistener interface, it is useful for specifying ContextMenu content when the view needs to create ContextMenu.

Layoutinflater.factory2

This interface has only one interface function:

publiconCreateView(View parent, String name, Context context, AttributeSet attrs);

It inherits from factory:

 public  interface  factory  { /** * Hook You can supply the is called whe         N inflating from a layoutinflater.         * Customize the tag names available in your XML * layout files. * * <p> * Note that it is good practice to prefix these custom names with your * package (i         . E., Com.coolcompany.apps) to avoid conflicts with system * names. */ public  View oncreateview  (String name, C    Ontext context, AttributeSet attrs); }

Used to interact with the Layoutinflater system in order to fit the Layoutinflater system. Implements the interface, can parse the XML in the Inflater time, the custom tag. The interface is called Layoutinflater, and the implementation of Layoutinflater is phonelayoutinflater. For window and layoutinflater structure can see this Android source code abstract factory-ipolicy.

In addition to activity, application and service have implemented the Componnentcallbacks interface, inherited Contextwrapper, in fact, can be used in the class adapter mode view.

Design Thinking

The application component itself should be an application environment (context), but it needs to meet the callback requirements of windows and other systems. We can usually directly implement the Window.callback interface, but the activity will be implemented Window.callback interface, then the activity will be more holistic, but the design intent to think too much here is a bit too far-fetched.

Summarize

From the Android application layer source collation, the activity of the class structure can be seen as an adapter mode, in the context of the application-based environment, To meet the Layoutinflater system (LAYOUTINFLATER.FACTORY2), the Window system (window.callback,window.onwindowdismissedcallback), the input system (KeyEvent.Cal Lback) interface requirements, in addition Componnentcallbacks is activitythread and Viewrootimpl required interface. The activity is viewed through the adapter pattern, and the interaction with the activity and other parts of the activity has a better understanding of the application Layer framework. In addition, there is a decorative mode to see the context, for the entire application layer structure will be clearer.

Android Source Adapter Mode---activity class structure

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.