解析View树、apk安装

apk安装

https://github.com/sucese/android-open-source-project-analysis/blob/master/doc/Android%E7%B3%BB%E7%BB%9F%E5%BA%94%E7%94%A8%E6%A1%86%E6%9E%B6%E7%AF%87/Android%E5%8C%85%E7%AE%A1%E7%90%86%E6%A1%86%E6%9E%B6/02Android%E5%8C%85%E7%AE%A1%E7%90%86%E6%A1%86%E6%9E%B6%EF%BC%9AAPK%E7%9A%84%E5%AE%89%E8%A3%85%E6%B5%81%E7%A8%8B.md


https://github.com/sucese/android-open-source-project-analysis/blob/master/doc/Android%E7%B3%BB%E7%BB%9F%E5%BA%94%E7%94%A8%E6%A1%86%E6%9E%B6%E7%AF%87/Android%E5%8C%85%E7%AE%A1%E7%90%86%E6%A1%86%E6%9E%B6/03Android%E5%8C%85%E7%AE%A1%E7%90%86%E6%A1%86%E6%9E%B6%EF%BC%9AAPK%E7%9A%84%E5%8A%A0%E8%BD%BD%E6%B5%81%E7%A8%8B.md
解析View树
解析merge标签,rInflate()方法会将merge下面的所有子View直接添加到根容器中,这里我们也理解了为什么merge标签可以达到简化布局的效果。

不是merge标签那么直接调用createViewFromTag()方法解析成布局中的视图,这里的参数name就是要解析视图的类型,例如:ImageView。
调用generateLayoutParams()f方法生成布局参数,如果attachToRoot为false,即不添加到根容器里,为View设置布局参数。
调用rInflateChildren()方法解析当前View下面的所有子View。
如果根容器不为空,且attachToRoot为true,则将解析出来的View添加到根容器中,如果根布局为空或者attachToRoot为false,那么解析出来的额View就是返回结果。返回解析出来的结果。

public abstract class LayoutInflater {
    
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
           synchronized (mConstructorArgs) {
               Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
   
               final Context inflaterContext = mContext;
               final AttributeSet attrs = Xml.asAttributeSet(parser);
               
               //Context对象
               Context lastContext = (Context) mConstructorArgs[0];
               mConstructorArgs[0] = inflaterContext;
               
               //存储根视图
               View result = root;
   
               try {
                   // 获取根元素
                   int type;
                   while ((type = parser.next()) != XmlPullParser.START_TAG &&
                           type != XmlPullParser.END_DOCUMENT) {
                       // Empty
                   }
   
                   if (type != XmlPullParser.START_TAG) {
                       throw new InflateException(parser.getPositionDescription()
                               + ": No start tag found!");
                   }
   
                   final String name = parser.getName();
                   
                   if (DEBUG) {
                       System.out.println("**************************");
                       System.out.println("Creating root view: "
                               + name);
                       System.out.println("**************************");
                   }
   
                   //1. 解析merge标签,rInflate()方法会将merge下面的所有子View直接添加到根容器中,这里
                   //我们也理解了为什么merge标签可以达到简化布局的效果。
                   if (TAG_MERGE.equals(name)) {
                       if (root == null || !attachToRoot) {
                           throw new InflateException("<merge /> can be used only with a valid "
                                   + "ViewGroup root and attachToRoot=true");
                       }
   
                       rInflate(parser, root, inflaterContext, attrs, false);
                   } else {
                       //2. 不是merge标签那么直接调用createViewFromTag()方法解析成布局中的视图,这里的参数name就是要解析视图的类型,例如:ImageView
                       final View temp = createViewFromTag(root, name, inflaterContext, attrs);
   
                       ViewGroup.LayoutParams params = null;
   
                       if (root != null) {
                           if (DEBUG) {
                               System.out.println("Creating params from root: " +
                                       root);
                           }
                           //3. 调用generateLayoutParams()f方法生成布局参数,如果attachToRoot为false,即不添加到根容器里,为View设置布局参数
                           params = root.generateLayoutParams(attrs);
                           if (!attachToRoot) {
                               // Set the layout params for temp if we are not
                               // attaching. (If we are, we use addView, below)
                               temp.setLayoutParams(params);
                           }
                       }
   
                       if (DEBUG) {
                           System.out.println("-----> start inflating children");
                       }
   
                       //4. 调用rInflateChildren()方法解析当前View下面的所有子View
                       rInflateChildren(parser, temp, attrs, true);
   
                       if (DEBUG) {
                           System.out.println("-----> done inflating children");
                       }
   
                       //如果根容器不为空,且attachToRoot为true,则将解析出来的View添加到根容器中
                       if (root != null && attachToRoot) {
                           root.addView(temp, params);
                       }
   
                       //如果根布局为空或者attachToRoot为false,那么解析出来的额View就是返回结果
                       if (root == null || !attachToRoot) {
                           result = temp;
                       }
                   }
   
               } catch (XmlPullParserException e) {
                   final InflateException ie = new InflateException(e.getMessage(), e);
                   ie.setStackTrace(EMPTY_STACK_TRACE);
                   throw ie;
               } catch (Exception e) {
                   final InflateException ie = new InflateException(parser.getPositionDescription()
                           + ": " + e.getMessage(), e);
                   ie.setStackTrace(EMPTY_STACK_TRACE);
                   throw ie;
               } finally {
                   // Don't retain static reference on context.
                   mConstructorArgs[0] = lastContext;
                   mConstructorArgs[1] = null;
   
                   Trace.traceEnd(Trace.TRACE_TAG_VIEW);
               }
   
               return result;
           }
     }
}

上面我们已经提到View树的解析是有rInflate()方法来完成的,我们接着来看看View树是如何被解析的。

public abstract class LayoutInflater {
    
    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        //1. 获取树的深度,执行深度优先遍历
        final int depth = parser.getDepth();
        int type;

        //2. 逐个进行元素解析
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();
            
            if (TAG_REQUEST_FOCUS.equals(name)) {
                //3. 解析添加ad:focusable="true"的元素,并获取View焦点。
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                //4. 解析View的tag。
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                //5. 解析include标签,注意include标签不能作为根元素。
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                //merge标签必须为根元素
                throw new InflateException("<merge /> must be the root element");
            } else {
                //6. 根据元素名进行解析,生成View。
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //7. 递归调用解析该View里的所有子View,也是深度优先遍历,rInflateChildren内部调用的也是rInflate()方
                //法,只是传入了新的parent View
                rInflateChildren(parser, view, attrs, true);
                //8. 将解析出来的View添加到它的父View中。
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) {
            //9. 回调根容器的onFinishInflate()方法,这个方法我们应该很熟悉。
            parent.onFinishInflate();
        }
    }
    
    //rInflateChildren内部调用的也是rInflate()方法,只是传入了新的parent View
    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

}

整个View树的解析流程,我们来概括一下:

  1. 获取树的深度,执行深度优先遍历.
  2. 逐个进行元素解析。
  3. 解析添加ad:focusable="true"的元素,并获取View焦点。
  4. 解析View的tag。
  5. 解析include标签,注意include标签不能作为根元素,而merge必须作为根元素。
  6. 根据元素名进行解析,生成View。
  7. 递归调用解析该View里的所有子View,也是深度优先遍历,rInflateChildren内部调用的也是rInflate()方法,只是传入了新的parent View。
  8. 将解析出来的View添加到它的父View中。
  9. 回调根容器的onFinishInflate()方法,这个方法我们应该很熟悉。

你可以看到,负责解析单个View的正是createViewFromTag()方法,我们再来分析下这个方法。

public abstract class LayoutInflater {

        View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
                boolean ignoreThemeAttr) {
            
            //1. 解析view标签。注意是小写view,这个不太常用,下面会说。
            if (name.equals("view")) {
                name = attrs.getAttributeValue(null, "class");
            }
    
            //2. 如果标签与主题相关,则需要将context与themeResId包裹成ContextThemeWrapper。
            if (!ignoreThemeAttr) {
                final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
                final int themeResId = ta.getResourceId(0, 0);
                if (themeResId != 0) {
                    context = new ContextThemeWrapper(context, themeResId);
                }
                ta.recycle();
            }
    
            //3. BlinkLayout是一种会闪烁的布局,被包裹的内容会一直闪烁,像QQ消息那样。
            if (name.equals(TAG_1995)) {
                // Let's party like it's 1995!
                return new BlinkLayout(context, attrs);
            }
    
            try {
                View view;
                
                //4. 用户可以设置LayoutInflater的Factory来进行View的解析,但是默认情况下
                //这些Factory都是为空的。
                if (mFactory2 != null) {
                    view = mFactory2.onCreateView(parent, name, context, attrs);
                } else if (mFactory != null) {
                    view = mFactory.onCreateView(name, context, attrs);
                } else {
                    view = null;
                }
                if (view == null && mPrivateFactory != null) {
                    view = mPrivateFactory.onCreateView(parent, name, context, attrs);
                }
    
                //5. 默认情况下没有Factory,而是通过onCreateView()方法对内置View进行解析,createView()
                //方法进行自定义View的解析。
                if (view == null) {
                    final Object lastContext = mConstructorArgs[0];
                    mConstructorArgs[0] = context;
                    try {
                        //这里有个小技巧,因为我们在使用自定义View的时候是需要在xml指定全路径的,例如:
                        //com.guoxiaoxing.CustomView,那么这里就有个.了,可以利用这一点判定是内置View
                        //还是自定义View,Google的工程师很机智的。😎
                        if (-1 == name.indexOf('.')) {
                            //内置View解析
                            view = onCreateView(parent, name, attrs);
                        } else {
                            //自定义View解析
                            view = createView(name, null, attrs);
                        }
                    } finally {
                        mConstructorArgs[0] = lastContext;
                    }
                }
    
                return view;
            } catch (InflateException e) {
                throw e;
    
            } catch (ClassNotFoundException e) {
                final InflateException ie = new InflateException(attrs.getPositionDescription()
                        + ": Error inflating class " + name, e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
    
            } catch (Exception e) {
                final InflateException ie = new InflateException(attrs.getPositionDescription()
                        + ": Error inflating class " + name, e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            }
        }
}

单个View的解析流程也很简单,我们来梳理一下:

  1. 解析View标签。
  2. 如果标签与主题相关,则需要将context与themeResId包裹成ContextThemeWrapper。
  3. BlinkLayout是一种会闪烁的布局,被包裹的内容会一直闪烁,像QQ消息那样。
  4. 用户可以设置LayoutInflater的Factory来进行View的解析,但是默认情况下这些Factory都是为空的。
  5. 默认情况下没有Factory,而是通过onCreateView()方法对内置View进行解析,createView()方法进行自定义View的解析。这里有个小技巧,因为 我们在使用自定义View的时候是需要在xml指定全路径的,例如:com.guoxiaoxing.CustomView,那么这里就有个.了,可以利用这一点判定是内置View 还是自定义View,Google的工程师很机智的。😎

关于onCreateView()与createView()

这两个方法在本质上都是一样的,只是onCreateView()会给内置的View前面加一个前缀,例如:android.widget,方便开发者在写内置View的时候,不用谢全路径名。 前面我们也提到了LayoutInflater是一个抽象类,我们实际使用的PhoneLayoutInflater,这个类的实现很简单,它重写了LayoutInflater的onCreatView()方法,该 方法就是做了一个给内置View加前缀的事情。

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };

    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        
        //循环遍历三种前缀,尝试创建View
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
                // In this case we want to let the base class take a crack
                // at it.
            }
        }
        return super.onCreateView(name, attrs);
    }
    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

这样一来,真正的View构建还是在createView()方法里完成的,createView()主要根据完整的类的路径名利用反射机制构建View对象,我们具体来 看看createView()方法的实现。

public abstract class LayoutInflater {
    
    public final View createView(String name, String prefix, AttributeSet attrs)
                throws ClassNotFoundException, InflateException {
        
            //1. 从缓存中读取构造函数。
            Constructor<? extends View> constructor = sConstructorMap.get(name);
            if (constructor != null && !verifyClassLoader(constructor)) {
                constructor = null;
                sConstructorMap.remove(name);
            }
            Class<? extends View> clazz = null;
    
            try {
                Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
    
                if (constructor == null) {
                    // Class not found in the cache, see if it's real, and try to add it
                    
                    //2. 没有在缓存中查找到构造函数,则构造完整的路径名,并加装该类。
                    clazz = mContext.getClassLoader().loadClass(
                            prefix != null ? (prefix + name) : name).asSubclass(View.class);
                    
                    if (mFilter != null && clazz != null) {
                        boolean allowed = mFilter.onLoadClass(clazz);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    }
                    //3. 从Class对象中获取构造函数,并在sConstructorMap做下缓存,方便下次使用。
                    constructor = clazz.getConstructor(mConstructorSignature);
                    constructor.setAccessible(true);
                    sConstructorMap.put(name, constructor);
                } else {
                    //4. 如果sConstructorMap中有当前View构造函数的缓存,则直接使用。
                    if (mFilter != null) {
                        // Have we seen this name before?
                        Boolean allowedState = mFilterMap.get(name);
                        if (allowedState == null) {
                            // New class -- remember whether it is allowed
                            clazz = mContext.getClassLoader().loadClass(
                                    prefix != null ? (prefix + name) : name).asSubclass(View.class);
                            
                            boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                            mFilterMap.put(name, allowed);
                            if (!allowed) {
                                failNotAllowed(name, prefix, attrs);
                            }
                        } else if (allowedState.equals(Boolean.FALSE)) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    }
                }
    
                Object[] args = mConstructorArgs;
                args[1] = attrs;
    
                //5. 利用构造函数,构建View对象。
                final View view = constructor.newInstance(args);
                if (view instanceof ViewStub) {
                    // Use the same context when inflating ViewStub later.
                    final ViewStub viewStub = (ViewStub) view;
                    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
                }
                return view;
    
            } catch (NoSuchMethodException e) {
                final InflateException ie = new InflateException(attrs.getPositionDescription()
                        + ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
    
            } catch (ClassCastException e) {
                // If loaded class is not a View subclass
                final InflateException ie = new InflateException(attrs.getPositionDescription()
                        + ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (ClassNotFoundException e) {
                // If loadClass fails, we should propagate the exception.
                throw e;
            } catch (Exception e) {
                final InflateException ie = new InflateException(
                        attrs.getPositionDescription() + ": Error inflating class "
                                + (clazz == null ? "<unknown>" : clazz.getName()), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
        }   
}

好了,讲到这里一个布局xml资源文件的查找和解析流程就分析完了。


 

相关推荐

  1. 解析Viewapk安装

    2024-04-10 05:40:02       30 阅读
  2. ArduPilot开源代码之AP_AHRS_View

    2024-04-10 05:40:02       21 阅读
  3. Android View滑动冲突解决方案

    2024-04-10 05:40:02       29 阅读
  4. ubuntu16 apt安装程序锁死解决

    2024-04-10 05:40:02       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-10 05:40:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-10 05:40:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-10 05:40:02       87 阅读
  4. Python语言-面向对象

    2024-04-10 05:40:02       96 阅读

热门阅读

  1. Qt中的触屏事件

    2024-04-10 05:40:02       39 阅读
  2. jenkins部署项目报错:certificate has expired

    2024-04-10 05:40:02       38 阅读
  3. Git同时拉取和推送多个分支

    2024-04-10 05:40:02       40 阅读
  4. 10个全面了解python自动化办公代码

    2024-04-10 05:40:02       35 阅读
  5. [蓝桥杯 2013 省 B] 翻硬币

    2024-04-10 05:40:02       28 阅读
  6. 富格林:堤防交易陷阱安全做单交易

    2024-04-10 05:40:02       36 阅读
  7. 边缘设备上的chatGPT

    2024-04-10 05:40:02       36 阅读
  8. Redis 常用命令以及结构

    2024-04-10 05:40:02       36 阅读
  9. Android Binder——Kernel层介绍(七)

    2024-04-10 05:40:02       34 阅读
  10. 【Unity优化】模型

    2024-04-10 05:40:02       29 阅读
  11. 掌握ChatGPT:打造高质量学术论文

    2024-04-10 05:40:02       31 阅读
  12. 2024【华南理工大学综合评价招生】解读

    2024-04-10 05:40:02       28 阅读