Hybrid App knowledge point collection _ native Webview knowledge, hybridwebview

Source: Internet
Author: User

Hybrid App knowledge point collection _ native Webview knowledge, hybridwebview
Native Webview knowledge: 1: Register related Permissions

 
  
   
  
 
2: Common webview Methods
GoBack () // backend goForward () // forward goBackOrForward (intsteps) // start from the current index or return to the specified steps in the history, if steps is negative, it is backward, and positive is forward canGoForward () // whether it can forward canGoBack () // whether it can be backward // clear the cached AchE (true) // clear the cache left by webpage access. Because the kernel cache is global, this method is not only for webview but for the entire application. clearHistory () // clears the access history of the current webview. Only the access history of the webview is deleted. clearFormData () // clear automatically filled form data. The data stored locally by WebView is not cleared. // Status onResume () // The WebView is activated. The response to the webpage onPause () can be normally executed. // The WebView is paused. The onPause action notifies the kernel to suspend all actions, for example, DOM parsing, plugin execution, and JavaScript Execution. PauseTimers () // pause layout, parsing, and javascripttimer of all webviews. Reduce CPU power consumption. ResumeTimers () // action to restore pauseTimers. Destroy () // destroy. When Activity is disabled, the music or video is still playing. It must be destroyed. // Reload the webpage reload () // load the local resource webView. loadUrl (" file:///android_asset/example.html "); // Load the webView of network resources. loadUrl ("www.xxx.com/index.html"); // Method for loading an html page locally on the mobile phone webView. loadUrl ("content: // com.android.html fileprovider/sdcard/test.html"); // you can load the html segment String data = "Html data"; webView. loadDataWithBaseURL (null, data, "text/html", "UTF-8", null); // disable hardware acceleration webView. setLayerType (View. LAYER_TYPE_SOFTWARE, null); // determines whether the WebView is scrolled to the top or low-end. // if (webView. getContentHeight () * webView. getScale () = (we BView. getHeight () + webView. getScrollY () {}// if (webView. getScrollY () = 0) {}// set the mobile phone to return the key listening public boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK & webView. canGoBack () {webView. goBack (); return true;} finish (); return super. onKeyDown (keyCode, event); // The Activity exits and destroys WebView protected void onDestroy () {if (webView! = Null) {webView. loadDataWithBaseURL (null, "", "text/html", "UTF-8", null); webView. clearHistory (); (ViewGroup) webView. getParent ()). removeView (webView); webView. destroy (); webView = null;} super. onDestroy ();}
3: WebSettings-webview general settings
WebSettings webSettings = webView. getSettings (); webSettings. setJavaScriptEnabled (true); // you can set JavaScriptwebSettings. setDefaultTextEncodingName ("UTF-8"); // sets the encoding format webSettings. setTextSize (TextSize. SMALLER); // set the font size: webSettings. setPluginsEnabled (true); // supports plug-in webSettings. setsuppzoom zoom (true); // supports scaling webSettings. setLayoutAlgorithm (WebSettings. layoutAlgorithm. SINGLE_COLUMN); // supports content relayout of webSettings. supportMult IpleWindows (); // webSettings for multiple windows. setAllowFileAccess (true); // sets webSettings for file access. setNeedInitialFocus (true); // when webview calls requestFocus, it sets the webSettings node for webview. setBuiltInZoomControls (true); // whether built-in button scaling and gesture "Pinch" Scaling are supported. If it is set to false, webview does not support webSettings. setJavaScriptCanOpenWindowsAutomatically (true); // supports opening webSettings in a new window through JS. setLoadsImagesAutomatically (true); // supports automatic loading of image webSettings. setDisplayZoomControls (false ); // Whether to hide the native zoom control webSettings. setDomStorageEnabled (true); // enable the DOM storage API function webSettings. setDatabaseEnabled (true); // enable the database storage API function webSettings. setAppCacheEnabled (true); // enable Application Caches function String cacheDirPath = getFilesDir (). getAbsolutePath () + APP_CACAHE_DIRNAME; webSettings. setAppCachePath (cacheDirPath); // set the Application Caches cache directory WebView screen adaptive webSettings. setUseWideViewPort (true ); WebSettings. setLoadWithOverviewMode (true); cache setting if (NetStatusUtil. isConnected (getApplicationContext () {webSettings. setCacheMode (WebSettings. LOAD_DEFAULT); // with a network, the cache-control determines whether to retrieve data from the network .} Else {webSettings. setCacheMode (WebSettings. LOAD_CACHE_ELSE_NETWORK); // No network, it is obtained from the local device, that is, offline loading} String appCachePath = getApplicationContext (). getCacheDir (). getAbsolutePath (); webSettings. setAppCachePath (appCachePath); // you can specify the cache data directory.
4: WebViewClient-handles various notifications and request events
WebViewClient webViewClient = new WebViewClient () {// hyperlink loading. When a webpage is opened, the system browser is not called, but displayed in this WebView. You can also capture the hyperlink url and perform related operations: public boolean shouldOverrideUrlLoading (WebView view, String url) {view. loadUrl (url); return true; // return true indicates loading in the current browser} // start loading public void onPageStarted (WebView view, String url, Bitmap favicon) {super. onPageStarted (view, url, favicon);} // public void onPageFinished (WebView view, String url) {super. onPageFinished (view, url);} // public void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error) {super. onReceivedError (view, request, error);} // public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {handler. proceed () ;}// call each resource on the page once to capture the page resource public void onLoadResource (WebView view, String url) {super. onLoadResource (view, url) ;}}; webView. setWebViewClient (webViewClient );
5: WebChromeClient-Javascript processing dialog box, website icon, website title, loading progress, etc.
WebChromeClient webChromeClient = new WebChromeClient () {// obtain the webpage loading progress public void onProgressChanged (WebView view, int newProgress) {if (newProgress <100) {String progress = newProgress + "%";} else {} super. onProgressChanged (view, newProgress);} // obtain the title public void onReceivedTitle (WebView view, String title) {super. onReceivedTitle (view, title); titleview. setText (title);} // get the title ICON public void OnReceivedIcon (WebView view, Bitmap icon) {super. onReceivedIcon (view, icon);} // warning box public boolean onJsAlert (WebView view, String url, String message, JsResult result) {if (message! = Null) {// TODO // capture the dialog box information in the webpage Toast. makeText (getApplicationContext (), message, Toast. LENGTH_LONG ). show ();} result. cancel (); // return true; // indicates the capture confirmation} // confirmation box. With this value, you can determine whether to confirm or cancel the click, and set it to true, cancel to false public boolean onJsConfirm (WebView view, String url, String message, JsResult result) {return super. onJsConfirm (view, url, message, result);} // The input box returns the value in the input box. Click Cancel to return null public boolean onJsPrompt (WebView view, String url, String message, string defaultValue, JsPromptResult result) {return super. onJsPrompt (view, url, message, defaultValue, result);} // locate public void onGeolocationPermissionsHidePrompt () {super. onGeolocationPermissionsHidePrompt ();} // locate public void onGeolocationPermissionsShowPrompt (final String origin, final GeolocationPermissions. callback callback) {callback. invoke (origin, true, false); // note a function. The second parameter is whether to agree to the positioning permission. The third parameter is whether the kernel wants to remember super. onGeolocationPermissionsShowPrompt (origin, callback);} // WebSettings must support multiple public boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {WebView. webViewTransport transport = (WebView. webViewTransport) resultMsg. obj; transport. setWebView (webView); resultMsg. sendToTarget (); return true;} public void onCloseWindow (WebView window) {super. onCloseWindow (window) ;}}; webView. setWebChromeClient (webChromeClient );
6. File Download is supported.
DownloadListener downloadListener = new DownloadListener() {    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {        Uri uri = Uri.parse(url);        Intent intent = new Intent(Intent.ACTION_VIEW, uri);        startActivity(intent);    }};webView.setDownloadListener(downloadListener);
JSBridge framework introduction:

The bridge between JS and native Communication is a good open-source framework. It is much easier and safer to use than native function calls, with a lower development cost. This is the link:
Https://github.com/firewolf-ljw/WebViewJSBridge
-1: Add dependency

dependencies {    compile 'com.github.lzyzsd:jsbridge:1.0.4'}
2: Use BridgeWebView instead of native webview in layout xml
 
     
 
3: key code example for passing data in JS and android
// Js transmits data to the key code (html) of android // js: function testClick1 () {var str1 = document. getElementById ("text1 "). value; var str2 = document. getElementById ("text2 "). value; window. webViewJavascriptBridge. callHandler ('submitfromweb', {'data': 'send json Data to the Android data'} // This type is of any type, function (responseData) {document. getElementById ("show "). innerHTML = "Android: =" + responseData});} // key android code (activity): bridgeWebV Iew. registerHandler ("submitFromWeb", new BridgeHandler () {public void handler (String data, CallBackFunction function) {Toast. makeText (MainActivity. this, "RegisterHandler from js data:" + data, Toast. LENGTH_LONG ). show (); function. onCallBack ("android RegisterHandler receives js data and returns it to you") ;}}); // android transmits data to js (register event listening) // key android code (activity): User user = new User (100, "aile"); bridgeWebView. callHandler ("functio NJs ", new Gson (). toJson (user), new CallBackFunction () {public void onCallBack (String data) {Toast. makeText (MainActivity. this, "return data from js:" + data, Toast. LENGTH_LONG ). show () ;}}); // js-side key code (html): // register the event listening function connectWebViewJavascriptBridge (callback) {if (window. webViewJavascriptBridge) {callback (WebViewJavascriptBridge)} else {document. addEventListener ('webviewjavascriptbridgeready ', Function () {callback (WebViewJavascriptBridge)}, false) ;}} connectWebViewJavascriptBridge (function (bridge) {bridge. init (function (message, responseCallback) {var data = {'json': 'js returns any data! '}; Document. getElementById ("init "). innerHTML = "data =" + message; responseCallback (data) ;}); // receives data from Android and returns the data bridge. registerHandler ("functionJs", function (data, responseCallback) {document. getElementById ("show "). innerHTML = ("Android: =" + data); var responseData = "Javascript return data"; responseCallback (responseData );});})

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.