WebView泄漏Activity的问题

android.os.ResultReceiver$MyResultReceiver.this$0
references org.chromium.content.browser.ContentViewCore$2$1.this$1(anonymous subcalss of android.os.ResultReceiver)
references org.chromium.content.browser.ContentViewCore$2.this$0
references org.chromium.content.browser.ContentViewCore.mContainerView
references android.webkit.WebView.mContext
leaks ***.WebActivity instance
android.view.accessibility.AccessibilityManager$1.this$0(anonymous sunclass of android.view.accessibility.IAccessibilityManagerClient$Stub)
references android.view.accessibility.AccessibilityManager.mAccesssibilityStateChangeListeners
references java.util.concurrent.CopyOnWriteArrayList.elements
references array java.lang.Object[].[1]
references org.chromium.content.browser.ContentViewCore.mContainerView
references android.webkit.WebView.mContext
leaks ***.WebActivity instance

WebView extends AbsoluteLayout 故拥有View的属性mContext属性,持有了Activity的对象

/**
 * The application environment this view lives in.
 * This field should be made private, so it is hidden from the SDK.
 * {@hide}
 */
@ViewDebug.ExportedProperty(deepExport = true)
protected Context mContext;

在WebView实例化的过程中,具体参考 2017-09-13-WebView实例化的问题,有句代码调用

    private void ensureProviderCreated() {
        checkThread();
        if (mProvider == null) {
            // As this can get called during the base class constructor chain, pass the minimum
            // number of dependencies here; the rest are deferred to init().
            mProvider = getFactory().createWebView(this, new PrivateAccess());
        }
    }

过程中实例化了 com.android.webview.chromium.WebViewChromiumFactoryProvider 并调用了

    @Override
    public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) {
        return new WebViewChromium(this, webView, privateAccess, mShouldDisableThreadChecking);
    }

然后实例化了 com.android.webview.chromium.WebViewChromium ,其中WebView的对象也传递到了这里

在WebViewChromium类中可以看到一个属性 mAwContents

// The WebView wrapper for ContentViewCore and required browser compontents.
    AwContents mAwContents;

在这个方法中 mAwContents 完成了实例化赋值

    private void initForReal() {
        AwContentsStatics.setRecordFullDocument(sRecordWholeDocumentEnabledByApi
                || mAppTargetSdkVersion < Build.VERSION_CODES.LOLLIPOP);

        mAwContents = new AwContents(mFactory.getBrowserContextOnUiThread(), mWebView, mContext,
                new InternalAccessAdapter(), new WebViewNativeDrawGLFunctorFactory(),
                mContentsClientAdapter, mWebSettings.getAwSettings(),
                new AwContents.DependencyFactory() {
                    @Override
                    public AutofillProvider createAutofillProvider(
                            Context context, ViewGroup containerView) {
                        return mFactory.createAutofillProvider(context, mWebView);
                    }
                });

        if (mAppTargetSdkVersion >= Build.VERSION_CODES.KITKAT) {
            // On KK and above, favicons are automatically downloaded as the method
            // old apps use to enable that behavior is deprecated.
            AwContents.setShouldDownloadFavicons();
        }

        if (mAppTargetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
            // Prior to Lollipop, JavaScript objects injected via addJavascriptInterface
            // were not inspectable.
            mAwContents.disableJavascriptInterfacesInspection();
        }

        // TODO: This assumes AwContents ignores second Paint param.
        mAwContents.setLayerType(mWebView.getLayerType(), null);
    }

在init方法中调用了initForReal

    // WebViewProvider methods --------------------------------------------------------------------

    @Override
    // BUG=6790250 |javaScriptInterfaces| was only ever used by the obsolete DumpRenderTree
    // so is ignored. TODO: remove it from WebViewProvider.
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void init(final Map<String, Object> javaScriptInterfaces,
            final boolean privateBrowsing) {
        ...
        mFactory.addTask(new Runnable() {
            @Override
            public void run() {
                initForReal();
                if (privateBrowsing) {
                    // Intentionally irreversibly disable the webview instance, so that private
                    // user data cannot leak through misuse of a non-privateBrowing WebView
                    // instance. Can't just null out mAwContents as we never null-check it
                    // before use.
                    destroy();
                }
            }
        });
    }

而init的调用者 就是WebView,在WebView的构造器中

    /**
     * @hide
     */
    @SuppressWarnings("deprecation")  // for super() call into deprecated base class constructor.
    protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes,
            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
        super(context, attrs, defStyleAttr, defStyleRes);
        ...
        ensureProviderCreated();
        mProvider.init(javaScriptInterfaces, privateBrowsing);
        ...
    }

这里的Provider实质上就是WebViewChromium的实例,其中上一句代码的ensureProviderCreated,就是去保证这个provider的存在。

为什么这里主要提到了 AwContents 呢?

org.chromium.content.browser.ContentViewCore

/**
 * Provides a Java-side 'wrapper' around a WebContent (native) instance.
 * Contains all the major functionality necessary to manage the lifecycle of a ContentView without
 * being tied to the view system.
 */
@JNINamespace("content")
public class ContentViewCore
        implements AccessibilityStateChangeListener, ScreenOrientationObserver
/**
 * Sets a new container view for this {@link ContentViewCore}.
 *
 * <p>WARNING: This method can also be used to replace the existing container view,
 * but you should only do it if you have a very good reason to. Replacing the
 * container view has been designed to support fullscreen in the Webview so it
 * might not be appropriate for other use cases.
 *
 * <p>This method only performs a small part of replacing the container view and
 * embedders are responsible for:
 * <ul>
 *     <li>Disconnecting the old container view from this ContentViewCore</li>
 *     <li>Updating the InternalAccessDelegate</li>
 *     <li>Reconciling the state of this ContentViewCore with the new container view</li>
 *     <li>Tearing down and recreating the native GL rendering where appropriate</li>
 *     <li>etc.</li>
 * </ul>
 */
public void setContainerView(ViewGroup containerView) {
    TraceEvent.begin();
    if (mContainerView != null) {
        mPastePopupMenu = null;
        mInputConnection = null;
        hidePopupsAndClearSelection();
    }

    mContainerView = containerView;
    mPositionObserver = new ViewPositionObserver(mContainerView);
    mContainerView.setWillNotDraw(false); // TODO(epenner): Remove (http://crbug.com/436689)
    mContainerView.setClickable(true);
    mViewAndroidDelegate.updateCurrentContainerView();
    for (ContainerViewObserver observer : mContainerViewObservers) {
        observer.onContainerViewChanged(mContainerView);
    }
    TraceEvent.end();    
}

有泄漏日志可以看到是因为ContentViewCore持有的mContainerView泄漏了,而mContainerView是由于 AwContents 的调用来赋值的

why? please go on ...

在AwContents的构造器中调用了 setNewAwContents()

    /* Common initialization routine for adopting a native AwContents instance into this
     * java instance.
     *
     * TAKE CARE! This method can get called multiple times per java instance. Code accordingly.
     * ^^^^^^^^^  See the native class declaration for more details on relative object lifetimes.
     */
    private void setNewAwContents(long newAwContentsPtr) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setNewAwContentsPreO(newAwContentsPtr);
        } else {
            // Move the TextClassifier to the new ContentViewCore.
            TextClassifier textClassifier =
                    mContentViewCore == null ? null : mContentViewCore.getCustomTextClassifier();
            setNewAwContentsPreO(newAwContentsPtr);
            if (textClassifier != null) mContentViewCore.setTextClassifier(textClassifier);
        }
    }

其中的 setNewAwContentsPre0()

    // Helper for setNewAwContents containing everything which applies to pre-O.
    private void setNewAwContentsPreO(long newAwContentsPtr) {
        ...
        mContentViewCore = new ContentViewCore(mContext, PRODUCT_VERSION);
        mViewAndroidDelegate = new AwViewAndroidDelegate(
                mContainerView, mContentsClient, mContentViewCore.getRenderCoordinates());
        initializeContentViewCore(mContentViewCore, mContext, mViewAndroidDelegate,
                mInternalAccessAdapter, webContents, new AwGestureStateListener(),
                mWindowAndroid.getWindowAndroid());
        nativeSetJavaPeers(mNativeAwContents, this, mWebContentsDelegate, mContentsClientBridge,
                mIoThreadClient, mInterceptNavigationDelegate, mAutofillProvider);
        mWebContents = mContentViewCore.getWebContents();
        ...
    }

这里实例化了ContentViewCore,并调用了方法initializeContentViewCore(),其中调用了ContentViewCore的initialize()方法,为ContentViewCore的mContainerView属性赋了值。注意这里,传入的参数是ViewAndroidDelegate viewDelegate,而mViewAndroidDelegate是由前一步来实例化的。

mViewAndroidDelegate = new AwViewAndroidDelegate(mContainerView, mContentsClient, mContentViewCore.getRenderCoordinates());

而AwContents这里的 mContainerView 就是 WebView .

那么到了这里基本上就完成了,由WebView的Context到ContentViewCore的mContainerView的过程。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,163评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,301评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,089评论 0 352
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,093评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,110评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,079评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,005评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,840评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,278评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,497评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,667评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,394评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,980评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,628评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,649评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,548评论 2 352

推荐阅读更多精彩内容