Hybrid App knowledge point collection

Posted by MorganM on Mon, 04 May 2020 01:33:41 +0200

Native Webview knowledge:

  • 1: Registration related authority
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  • 2:webview common methods
goBack() //Back off 
goForward() //Forward 
goBackOrForward(intsteps) //Take the current index as the starting point to advance or retreat to the steps specified in the history. If the steps is negative, it is backward, and if the steps is positive, it is forward 
canGoForward() //Can we move forward 
canGoBack() //Can I go back

//Clear cache 
clearCache(true) //Clear the cache left by web access. Because the kernel cache is global, this method is not only for webview but for the whole application 
clearHistory() //Clear the history of the current webview access, only all records in the webview access history except the current access record 
clearFormData() //Clearing the auto complete populated form data does not clear the data stored in WebView locally.

onResume() //Activate WebView to active state, and the response of the web page can be executed normally 
onPause() //WebView is in a paused state. The onPause action tells the kernel to pause all actions, such as DOM parsing, plugin execution, and JavaScript execution. 
pauseTimers() //Pause layout, parsing and JavaScript timer of all webview s. Reduce CPU power consumption. 
resumeTimers() //Action when resuming pauseTimers. 
destroy() //Destroy. When the Activity is closed, music or video is still playing. It must be destroyed.

//Reload web page 

//Load local resources

//Load network resources

//The method of loading a local html page of mobile phone 

//html fragments can be loaded
String data = " Html data";
webView.loadDataWithBaseURL(null,data, "text/html", "utf-8",null);

//Turn off hardware acceleration
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

//Determine whether WebView scrolls to the top or the bottom
// Already at the bottom
if (webView.getContentHeight() * webView.getScale() == (webView.getHeight() + webView.getScrollY())) {
// At the top
if(webView.getScrollY() == 0){

//Set the back key monitor of mobile phone
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
        return true;
    return super.onKeyDown(keyCode, event);

//Activity exit destroy WebView 
protected void onDestroy() {
    if (webView != null) {
        webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

        ((ViewGroup) webView.getParent()).removeView(webView);
        webView = null;
  • 3:WebSettings – webview general settings
WebSettings webSettings = webView.getSettings();

webSettings.setJavaScriptEnabled(true);//Set up JavaScript support
webSettings.setDefaultTextEncodingName("utf-8");//Set encoding format
webSettings.setTextSize(TextSize.SMALLER);//Set font size:
webSettings.setPluginsEnabled(true); //Support Plug-Ins
webSettings.setSupportZoom(true);  //Supports scaling
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //Support content re layout
webSettings.supportMultipleWindows();  //Multiple windows
webSettings.setAllowFileAccess(true);  //Set access to files
webSettings.setNeedInitialFocus(true); //Set the node for webview when it calls requestFocus
webSettings.setBuiltInZoomControls(true); //Whether the built-in button scaling and gesture "pinch" scaling are supported. If it is set to false, webview does not support scaling
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //Support to open new windows through JS
webSettings.setLoadsImagesAutomatically(true);  //Support for automatically loading pictures
webSettings.setDisplayZoomControls(false);      //Hide native zoom controls or not
webSettings.setDomStorageEnabled(true);//Enable DOM storage API function
webSettings.setDatabaseEnabled(true);//Enable database storage API function
webSettings.setAppCacheEnabled(true); //Turn on the Application Caches function

String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
webSettings.setAppCachePath(cacheDirPath); //Set Application Caches cache directory

WebView Screen adaptation

//Cache settings
if (NetStatusUtil.isConnected(getApplicationContext())) {
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//If there is a network, the cache control determines whether to retrieve data from the network.
} else {
    webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //If there is no network, it will be obtained locally, i.e. loaded offline
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webSettings.setAppCachePath(appCachePath);//Set cache data directory
  • 4:WebViewClient – handles various notification and request events
WebViewClient webViewClient = new WebViewClient(){

    //Hyperlinks are loaded and displayed in this WebView instead of calling the system browser when opening a web page. You can also capture hyperlink URLs for related operations
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;    //Return true to load in the current browser

    //Page start loading
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

    //End of web page loading
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

    //Page load failed
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);

    //Support for Https
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

    //Once for each resource in the page to capture the page resource
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
  • 5:WebChromeClient - handle Javascript dialog box, website icon, website title, loading progress, etc
WebChromeClient webChromeClient = new WebChromeClient(){
    //Get page load progress
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress < 100) {
            String progress = newProgress + "%";
        } else {
        super.onProgressChanged(view, newProgress);

    //Get title
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);

    //Get 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) {
            //Capture pop-up information in web pages
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        result.cancel();   //
        return true;       //Indicates confirm to capture

    //Confirmation box, through which you can judge whether to confirm or cancel when clicking. It is determined to be true and cancel to be false
    public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
        return super.onJsConfirm(view, url, message, result);

    //Input box, the value in the input box will be returned. 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);
    public void onGeolocationPermissionsHidePrompt() {
    public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);  //Pay attention to a function. The second parameter is whether to agree to the location permission. The third parameter is whether you want the kernel to remember
        super.onGeolocationPermissionsShowPrompt(origin, callback);

    //WebSettings to support multiple windows
    public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        return true;

    public void onCloseWindow(WebView window) {

  • 6: Support file download
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);


Introduction to JSBridge framework:

The communication bridge between JS and native is a good open source framework, which is much more convenient and safer than native function calls, and has lower development cost. This is the link:
-1: add dependency

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'
  • 2: Using BridgeWebView instead of native webview in layout xml
        android:layout_height="match_parent" >
  • 3:JS and android deliver data key code examples
//js transfers data to android
//js key code (html):
function testClick1() {
            var str1 = document.getElementById("text1").value;
            var str2 = document.getElementById("text2").value;
                , {'Data': 'json Data to Android end'}  //This type is any type
                , function(responseData) {
                    document.getElementById("show").innerHTML = "Android end: =" + responseData
//android key code (activity):
bridgeWebView.registerHandler("submitFromWeb", new BridgeHandler() {
            public void handler(String data, CallBackFunction function) {
                Toast.makeText(MainActivity.this, "RegisterHandler Come from js Data for:"+ data, Toast.LENGTH_LONG).show();
                function.onCallBack("android end RegisterHandler Received js Data for,Send back data to you");

//android passes data to JS (register event listening)
//android key code (activity):
User user = new User(100, "aile");
        bridgeWebView.callHandler("functionJs", new Gson().toJson(user), new CallBackFunction() {
            public void onCallBack(String data) {
                Toast.makeText(MainActivity.this, "Come from js Data returned from:" + data, Toast.LENGTH_LONG).show();
//js key code (html):
         //Register event listening
        function connectWebViewJavascriptBridge(callback) {
            if (window.WebViewJavascriptBridge) {
            } else {
                    , function() {

        connectWebViewJavascriptBridge(function(bridge) {
            bridge.init(function(message, responseCallback) {
                var data = {
                    'json': 'JS Return any data!'
                 document.getElementById("init").innerHTML = "data = " + message;
            //Here we receive the data from Android and send back the data
            bridge.registerHandler("functionJs", function(data, responseCallback) {
                document.getElementById("show").innerHTML = ("Android end: = " + data);
                var responseData = "Javascript Return data";

Topics: Android Javascript network github