Cordova Android Source Analysis Series II (Cordovawebview related class analysis)

Source: Internet
Author: User

This article is Cordova Android source code Analysis series of the second article, the main analysis of Cordovawebview and Cordovawebviewclient class, through the analysis of code can know the Web page loading process, error, multithreading and so on.

Cordovawebview class Analysis

The Cordovawebview class inherits the Android WebView class, which is a natural implementation of a total of more than 1000 lines of code. Contains PlugInManager pluginmanager,broadcastreceiver receiver,cordovainterface Cordova, Cordovawebviewclient viewClient , Cordovachromeclient chromeclient,nativetojsmessagequeue jsmessagequeue, Exposedjsapi ExposedJsApi, Important member variables, such as Cordovaresourceapi Resourceapi, are associated with other core classes.

4 constructors are available: Cordovawebview (context context), Cordovawebview (context context, AttributeSet attrs, int Defstyle, Boolean privatebrowsing), corresponding to the corresponding constructors for the Android WebView class, respectively. These constructors first call the corresponding constructor of WebView, and then initialize the Cordova class variable, calling its own setwebchromeclient,initwebviewclient,loadconfiguration, in turn, as appropriate. Setup method.

The Setwebchromeclient method sets Webchromeclient, calling the Setwebchromeclient method of the WebView class.

Depending on the version of the Android SDK, the Initwebviewclient method calls Setwebviewclient, which, for Icecreamsandwich version, calls Setwebviewclient (new Icecreamcordovawebviewclient (This.cordova, this)). For the time being do not know the specific reason.

    /**     * Set the webviewclient, but provide special case handling for Icecreamsandwich.     */    private void Initwebviewclient (Cordovainterface Cordova) {        if (Android.os.Build.VERSION.SDK_INT < Android.os.Build.VERSION_CODES. Honeycomb | |                Android.os.Build.VERSION.SDK_INT > Android.os.Build.VERSION_CODES. JELLY_BEAN_MR1)        {            this.setwebviewclient (new Cordovawebviewclient (This.cordova, this));        }        else        {            this.setwebviewclient (new Icecreamcordovawebviewclient (This.cordova, this));        }    }


The Setup method works by initializing WebView. First enable JavaScript, just as we use webview ourselves:

        WebSettings settings = This.getsettings ();        Settings.setjavascriptenabled (true);        Settings.setjavascriptcanopenwindowsautomatically (true);        Settings.setlayoutalgorithm (Layoutalgorithm.normal);

Set up NAV dump for HTC 2.x Devices Series devices (for ICS disable, downgrade for Jellybean 4.2), implemented by reflection to get the Setnavdump method, If the device model contains HTC and the SDK version is less than one (Honeycomb), set Setnavdump (true).

Settings do not save the page form data, we can rest assured!

We don ' t save any form data in the application

Settings.setsaveformdata (FALSE);

Settings.setsavepassword (FALSE);

The following is the setting DatabasePath, whether to open debug mode, etc., called the Setdomstorageenabled,setgeolocationenabled,setappcachemaxsize,setappcachepath , setappcacheenabled and other websetting methods, from the name can easily understand the role.

Then a receiver is registered and the Intentfilter action of the listener is action_configuration_changed.

The PLUGINMANAGER,JSMESSAGEQUEUE,EXPOSEDJSAPI,RESOURCEAPI member variable was finally initialized.

Below we look at the Web page loading process, first look at the Loadurl method, it is actually called the Loadurlintoview method. The Loadurlintoview method first initializes the plug-in manager PlugInManager and then creates 2 runnable objects Loaderror and Timeoutcheck, Loaderror is used to notify the client of viewclient error messages, Timeoutcheck is used to check the page timeout, and finally calls Loadurlnow (URL) in the UI thread. Note The Timeoutcheck task is running in the thread pool. The Loadurlnow method eventually calls the WebView Loadurl (URL) method.

        Load URL        this.cordova.getActivity (). Runonuithread (New Runnable () {public            void run () {                Cordova.getthreadpool (). Execute (timeoutcheck);                Me.loadurlnow (URL);            }        });


Cordovawebviewclient class Analysis

The Cordovawebviewclient class inherits the Android Webviewclient and implements the Cordovawebview fallback function, which is triggered during the rendering of the document, such as onpagestarted (), Shouldoverrideurlloading () and other methods.

The method public Boolean shouldoverrideurlloading (WebView view, String URL) provides the opportunity for the Web app on the upper level to handle URL loading, and the Exec method in JS is intercepted, Given to the Handleexecurl (URL) method for processing. If the URI starts with Tel,sms,geo,market and so on, the relevant app processing is enabled through intent. If it's our own app or file, a new activity will start, including a new Cordovawebview, which can be returned to our app when we press the back key.

method public void onpagestarted (WebView view, String URL, Bitmap favicon) notifies the app page to start loading, and if the page contains frameset or IFRAME, these embedded pages load when is not triggered by onpagestarted. By This. Appview The . PostMessage method sends notifications to all plug-ins.

@Override public    void onpagestarted (WebView view, String URL, Bitmap favicon) {        super.onpagestarted (view, URL, Favicon);        Iscurrentlyloading = true;        LOG.D (TAG, "onpagestarted (" + URL + ")");        Flush stale messages.        This.appView.jsMessageQueue.reset ();        Broadcast message that page has loaded        this.appView.postMessage ("onpagestarted", url);        Notify all plugins of the navigation, so they can clean up if necessary.        if (This.appView.pluginManager! = null) {            this.appView.pluginManager.onReset ();}    }


The implementation of the public void onpagefinished (WebView view, String URL) is similar to onpagestarted, and it is important to note that the delay of 2 seconds after the page load is complete will stop the progress bar. The goal is to prevent the occurrence of JS errors or Cordova without initialization, by creating a thread, sleep 2s, and then sending a notification on the UI thread spinner stop to all plugins.


Cordovaresourceapi class Analysis

Cordova Android uses the OKHTTP framework as the network access infrastructure, Okhttp is a Java http+spdy client development package and also supports Android.

The Cordovaresourceapi encapsulates the Okhttp and provides 3 main features:

1. Helper methods for reading and writing URLs

such as processing assets, resources, content providers, files, data URIs, http [s]

can be used to query file type and content length

2. Allow plugin redirection URL

3. Exposing the Okhttp library Cordova comes with the Createhttpconnection () method


This class is relatively simple, first creating static variables Okhttpclient httpclient and Jsthread, so that the entire application has only one okhttp instance, is a lightweight implementation.

Then the constructor is


Public Cordovaresourceapi (context context, PlugInManager PlugInManager) {

This.contentresolver = Context.getcontentresolver ();

This.assetmanager = Context.getassets ();

This.pluginmanager = PlugInManager;

}

You can see that the class member variables of Contentresolver,assetmanager and PlugInManager are initialized.

Public Uri Remapuri (Uri uri) {


Assertnonrelative (URI);

Uri Pluginuri = Pluginmanager.remapuri (URI);

return Pluginuri! = null? Pluginuri:uri;

}

A method for redirecting URLs, the URL must be an absolute path, and the final implementation is in Pluginmanager.remapuri (URI)

@Override public void onpagefinished (WebView view, String URL) {super.onpagefinished (view, URL);        Ignore excessive calls.        if (!iscurrentlyloading) {return;        } iscurrentlyloading = false;        LOG.D (TAG, "onpagefinished (" + URL + ")"); /** * Because of a timing issue we need to clear the history in onpagefinished as well as * onpagestarted . However we only want to does this if the Doclearhistory Boolean was set to * true. You see if you load a URLs with a # in it which are common in jQuery applications * onpagestared are not called.         Clearing the would break jQuery apps.            */if (this.doclearhistory) {view.clearhistory ();        This.doclearhistory = false;        }//Clear timeout flag this.appview.loadurltimeout++;        Broadcast message that page has loaded this.appView.postMessage ("onpagefinished", url); Make App visible after 2 sec in case there is a JS error and Cordova JS never initialized correctly if (THIS.APPVIEW.G                    Etvisibility () = = view.invisible) {Thread t = new Thread (new Runnable () {public void run () {                        try {thread.sleep (2000);                                Cordova.getactivity (). Runonuithread (New Runnable () {public void run () {                            Appview.postmessage ("Spinner", "Stop");                    }                        });            } catch (Interruptedexception e) {}}});        T.start ();         }//Shutdown if blank loaded if (Url.equals ("About:blank")) {Appview.postmessage ("exit", NULL); }    }



The public file Mapuritofile (URI uri) returns the URL to the file, the URL can be file://or the content format, and the method must run the assertion of the background thread and cannot run on the UI thread and the WebCore thread.


Method public Openforreadresult Openforread (Uri Uri, Boolean Skipthreadcheck) throws IOException is used to open the specified URI, Skipthreadcheck sets whether to check whether the background thread is running, the return value Openforreadresult is a static inner class, provides uri,inputstream,mimetype, length of content, Assetfiledescriptor parameters, convenient for us to use.

The next article analyzes the Cordova plug-in architecture, mainly involving Cordovaplugin and PlugInManager classes.



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.