WebView使用问题

线程

AOS要求WebView的调用线程必须一致,否则会抛出异常,提示"All WebView methods must be called on the same thread. "。WebView在初始化时,mWebViewThread会记录当前的初始化线程,因为webview是一个UI控件,我们一般会在主线程中初始化,所以很多情况下这个成员变量就是当前的主线程。之后,在调用webview的相关方法时,都会首先调用checkThread()方法检测线程是否一致,即检测两个线程的looper对象。如果不相同,会有异常抛出。

    private final Looper mWebViewThread = Looper.myLooper();

    private void checkThread() {
        // Ignore mWebViewThread == null because this can be called during in the super class
        // constructor, before this class's own constructor has even started.
        if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) {
            Throwable throwable = new Throwable(
                    "A WebView method was called on thread '" +
                    Thread.currentThread().getName() + "'. " +
                    "All WebView methods must be called on the same thread. " +
                    "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() +
                    ", FYI main Looper is " + Looper.getMainLooper() + ")");
            Log.w(LOGTAG, Log.getStackTraceString(throwable));
            StrictMode.onWebViewMethodCalledOnWrongThread(throwable);

            if (sEnforceThreadChecking) {
                throw new RuntimeException(throwable);
            }
        }
    }

你可能感兴趣的:(WebView使用问题)