View.getContext()从何而来

一、引子

曾经遇到一个问题,使用View的Context变量调用startActivity()方法,出现一个异常:“Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?”。百度了下异常的原因,是由于调用startActivity()的Context为Application,而非Activity。
在ContextImpl中找了下,报异常的位置在:

    @Override
    public void startActivity(Intent intent, Bundle options) {
        warnIfCallingFromSystemProcess();

        // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
        // generally not allowed, except if the caller specifies the task id the activity should
        // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
        // maintain this for backwards compatibility.
        final int targetSdkVersion = getApplicationInfo().targetSdkVersion;

        if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
                && (targetSdkVersion < Build.VERSION_CODES.N
                        || targetSdkVersion >= Build.VERSION_CODES.P)
                && (options == null
                        || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
            throw new AndroidRuntimeException(
                    "Calling startActivity() from outside of an Activity "
                            + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
                            + " Is this really what you want?");
        }
        mMainThread.getInstrumentation().execStartActivity(
                getOuterContext(), mMainThread.getApplicationThread(), null,
                (Activity) null, intent, -1, options);
    }

其中getLaunchTaskId方法相关信息如下:

    private int mLaunchTaskId = -1;
    
    public int getLaunchTaskId() {
        return mLaunchTaskId;
    }
    
    /**
     * The task id the activity should be launched into.
     * @hide
     */
    private static final String KEY_LAUNCH_TASK_ID = "android.activity.launchTaskId";
    public ActivityOptions(Bundle opts) {    
            // ... 
            mLaunchTaskId = opts.getInt(KEY_LAUNCH_TASK_ID, -1);
            // ... 
    }        

可以看到,在intent未使用Intent.FLAG_ACTIVITY_NEW_TASK,且android Api在24以下或27以上的机型上,如果bundle为空,或bundle所在的taskId为-1,会报异常。这样可以大致推测,使用Application的Context启动activity,由于没有Activity的taskId信息,无法确定新Activity的taskId,所以抛出异常。
那为什么View的Context有时是Activity,有时是Application呢?

二、查找
(一)从LayoutInflater.from(Context context)方法开始
public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return LayoutInflater;
    }

需要了解下Context、ContextImpl、ContextWrapper相关知识。
Context.getSystemService其实直接调用了ContextImpl类的getSystemService方法

    @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

直接调用了SystemServiceRegistry类的getSystemService()方法

    public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }

其中SYSTEM_SERVICE_FETCHERS是SystemServiceRegistry类的静态变量,它的初始化中包含

        registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                new CachedServiceFetcher<LayoutInflater>() {
            @Override
            public LayoutInflater createService(ContextImpl ctx) {
                return new PhoneLayoutInflater(ctx.getOuterContext());
            }});

ctx.getOuterContext()其实就是LayoutInflater.from()传入的Context参数。
看下CachedServiceFetcher类

    static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
        @Override
        public final T getService(ContextImpl ctx) {
            final Object[] cache = ctx.mServiceCache;
            
                    // Return it if we already have a cached instance.
                    T service = (T) cache[mCacheIndex];
                    if (service != null || gates[mCacheIndex] == ContextImpl.STATE_NOT_FOUND) {
                        return service;
                    }

                    T service = null;
                    try {
                        service = createService(ctx);
                        newState = ContextImpl.STATE_READY;
                    } catch (ServiceNotFoundException e) {
                        onServiceNotFound(e);
                    }
                    return service;
        }

        public abstract T createService(ContextImpl ctx) throws ServiceNotFoundException;
    }

从传入的ContextImpl中获取该Context是否已经生成了LayoutInflater,如果未生成,则通过createService()方法创建。
所以SystemServiceRegistry类的getSystemService()返回的是PhoneLayoutInflater,使用的LayoutInflater.from()方法传入的Context变量。绕了一圈,从Context绕到ContextImpl,又绕回到了Context。

(二)拿到LayoutInflater,可以去inflate()了

虽然上一步中,生成的是PhoneLayoutInflater,但inflate()方法使用的仍然是基类LayoutInflater的inflate()方法

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

看下inflate()方法

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                final String name = parser.getName();

                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 {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        // Create layout params that match root, if supplied
                        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);
                        }
                    }

                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    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;
            }

            return result;
        }
    }

其中关注下createViewFromTag()方法,

            final Context inflaterContext = mContext;
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

传入的Context参数为LayoutInflater的mContext变量。

三、结论

View的Context与LayoutInflater.from()传入的Context保持一致。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值