001 - create a simple browser using Hongmeng WebView step 1

Posted by zipp on Fri, 04 Mar 2022 05:02:51 +0100

  1. Open the official website and find the document of WebView (not supported by the simulator)

    Hongmeng webview's Development Guide (original link, easy to identify and click): https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158


2. Create a Page Ability and make the basic layout well

Here is the code

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">
    <DirectionalLayout
        ohos:height="30vp"
        ohos:width="match_parent"
        ohos:orientation="horizontal">
        <TextField
            ohos:id="$+id:text_webView_Url"
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:background_element="$graphic:background_ability_simple_web_view"
            ohos:focus_border_enable="true"
            ohos:hint="Please enter the web address"
            ohos:max_text_lines="1"
            ohos:multiple_lines="false"
            ohos:scrollable="true"
            ohos:text="www.harmonyos.com"
            ohos:text_size="50"
            ohos:weight="1"
            />
        <Button
            ohos:id="$+id:button_webview_surf"
            ohos:height="match_content"
            ohos:width="60vp"
            ohos:background_element="$graphic:button_element"
            ohos:text="Jump"
            ohos:text_size="50"/>
    </DirectionalLayout>
    <ProgressBar
        ohos:id="$+id:other_webView_progressBar"
        ohos:height="10vp"
        ohos:width="match_parent"
        ohos:visibility="hide">
    </ProgressBar>
    <ohos.agp.components.webengine.WebView
        ohos:id="$+id:webview_webview_webview"
        ohos:height="match_parent"
        ohos:width="match_parent"
        ohos:weight="1">
    </ohos.agp.components.webengine.WebView>
    <DirectionalLayout
        ohos:height="30vp"
        ohos:width="match_parent"
        ohos:orientation="horizontal">
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:orientation="horizontal"
            ohos:weight="1">
            <Button
                ohos:id="$+id:button_webview_back"
                ohos:height="match_content"
                ohos:width="match_parent"
                ohos:background_element="$graphic:button_element"
                ohos:layout_alignment="horizontal_center"
                ohos:text="backward"
                ohos:text_size="50"
                >
            </Button>
        </DirectionalLayout>
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:orientation="horizontal"
            ohos:weight="1">
            <Button
                ohos:id="$+id:button_webview_refresh"
                ohos:height="match_content"
                ohos:width="match_parent"
                ohos:background_element="$graphic:button_element"
                ohos:layout_alignment="horizontal_center"
                ohos:text="Refresh"
                ohos:text_size="50">
            </Button>
        </DirectionalLayout>
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:orientation="horizontal"
            ohos:weight="1">
            <Button
                ohos:id="$+id:button_webview_forward"
                ohos:height="match_content"
                ohos:width="match_parent"
                ohos:background_element="$graphic:button_element"
                ohos:layout_alignment="horizontal_center"
                ohos:text="forward"
                ohos:text_size="50">
            </Button>
        </DirectionalLayout>
    </DirectionalLayout>
</DirectionalLayout>
 
  1. Fix the basic button events

    Serial number Button function
    1 Jump Open the URL in the text box
    2 back off After clicking the new link in webview, I want to go back and have a look
    3 Refresh In the past, people used to use it when the Internet was bad and the pictures of beautiful women couldn't come out. Now, generally, after sending a post, the author will click it to see if anyone likes it
    4 forward It is associated with backward, that is, click a new link, go back and look, still think the new link is better, and then move forward

    code

        Component.ClickedListener clickedListener = new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int componentId = component.getId();
                switch (componentId) {
                    case ResourceTable.Id_button_webview_surf: {
                        urlAddress = textWebViewUrl.getText();
                        if (urlAddress.isEmpty()) {
                            return;
                        }
                        if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) {
                            urlAddress = FinalValue.URL_HTTPS + urlAddress;
                        }
                        webView.load(urlAddress);
    
                       
                    }
                    break;
                    case ResourceTable.Id_button_webview_back: {
                        if (webView.getNavigator().canGoBack()) {
                            webView.getNavigator().goBack();
                        }
                    }
                    break;
                    case ResourceTable.Id_button_webview_refresh: {
                        webView.reload();
                    }
                    break;
                    case ResourceTable.Id_button_webview_forward: {
                        if (webView.getNavigator().canGoForward()) {
                            webView.getNavigator().goForward();
                        }
                    }
                    break;
                    default: {
                        System.out.println("No pages selected");
                    }
                    break;
                }
            }
        };
    
    
  • Complete the WebView according to the requirements above the document

    There's nothing to say, just the rules I added to the line of code calling the load method to open the URL, and I also got a function associated with the progress bar

      //Allow javascript interaction
    
                        WebConfig webConfig = webView.getWebConfig();
                        webConfig.setDataAbilityPermit(true);
                        webConfig.setJavaScriptPermit(true);
                        webConfig.setLoadsImagesPermit(true);
                        webConfig.setMediaAutoReplay(true);
                        webConfig.setLocationPermit(true);
                        webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE);
    
                        webView.setWebAgent(new WebAgent() {
                            @Override
                            public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
                                super.onLoadingPage(webView, url, favicon);
                                // Here I added a function to update the url of the new page in the url text box
                                if (url != urlAddress) {
                                   textWebViewUrl.setText(url);
                                }
    
                            }
    
                            @Override
                            public void onPageLoaded(WebView webView, String url) {
                                super.onPageLoaded(webView, url);
                                // Customized processing after page loading
                            }
    
                            @Override
                            public void onLoadingContent(WebView webView, String url) {
                                super.onLoadingContent(webView, url);
                                // Custom processing when loading resources
                            }
    
                            @Override
                            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                                super.onError(webView, request, error);
                                // Custom processing when an error occurs
                            }
                        });
                        webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) {
                            @Override
                            public void onTitleUpdated(WebView webView, String title) {
                                super.onTitleUpdated(webView, title);
                                // Custom processing when Title Changes
                            }
    
                            @Override
                            public void onProgressUpdated(WebView webView, int newProgress) {
                                super.onProgressUpdated(webView, newProgress);
                                if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) {
                                    otherWebViewProgressBar.setVisibility(Component.VISIBLE);
                                    otherWebViewProgressBar.setProgressValue(newProgress);
                                } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) {
                                    otherWebViewProgressBar.setVisibility(Component.HIDE);
                                }
                                // Custom processing when loading progress change
                            }
                        });
    
     
  • Finished? Is there anything else?

    If you copy the code from above, it's probably done However, I use memory, but the code doesn't go back, so I still need to explain the problems in the steps here, so that students who don't copy the code can run out of an interface It is mainly reflected as follows:

    1. Permission configuration, not much

       "reqPermissions": [
            {
              "name": "ohos.permission.INTERNET"
            }
          ]
      
       
  • WebView in xml should have package name

      <ohos.agp.components.webengine.WebView
            ohos:id="$+id:webview_webview_webview"
            ohos:height="match_parent"
            ohos:width="match_parent"
            ohos:weight="1">
        </ohos.agp.components.webengine.WebView>
     
    1. If not written according to the package name above:

      • There is no WebView interface after the real machine runs Not even if weight=1
      • After clicking the jump button, PageAbility will flash back to the first screen (the page calling it)

    Completion effect: https://www.bilibili.com/video/BV1tK4y1o7Hz/

  • Complete code

    • layout

      All the steps with serial number 2 are pasted

    • Button background

      <?xml version="1.0" encoding="UTF-8" ?>
      <shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
             ohos:shape="rectangle">
          <corners
              ohos:radius="20"/>
          <solid
              ohos:color="#70dbdb"/>
      </shape>
      
       
  • java code

    package com.javaaier.family.huawei.slice;
    
    import com.javaaier.family.huawei.ResourceTable;
    import com.javaaier.family.huawei.common.FinalValue;
    import ohos.aafwk.ability.AbilitySlice;
    import ohos.aafwk.content.Intent;
    import ohos.agp.components.*;
    import ohos.agp.components.webengine.*;
    import ohos.media.image.PixelMap;
    
    /**
     * @Author JavaAIer
     * @Description : webview Control example 1: it is used to simply test the usage of webview < br / >
     * 001 Simple webview example
     * @Date: 2021/4/16
     */
    public class SimpleWebViewAbilitySlice extends AbilitySlice {
        String urlAddress;
    
    
        ProgressBar otherWebViewProgressBar;
        TextField textWebViewUrl;
        Button buttonWebViewSurf, buttonWebViewBack, buttonWebViewRefresh, buttonWebViewForward;
        WebView webView;
    
        Component.ClickedListener clickedListener = new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int componentId = component.getId();
                switch (componentId) {
                    case ResourceTable.Id_button_webview_surf: {
                        urlAddress = textWebViewUrl.getText();
                        if (urlAddress.isEmpty()) {
                            return;
                        }
                        if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) {
                            urlAddress = FinalValue.URL_HTTPS + urlAddress;
                        }
                        webView.load(urlAddress);
    
                        //Allow javascript interaction
    
                        WebConfig webConfig = webView.getWebConfig();
                        webConfig.setDataAbilityPermit(true);
                        webConfig.setJavaScriptPermit(true);
                        webConfig.setLoadsImagesPermit(true);
                        webConfig.setMediaAutoReplay(true);
                        webConfig.setLocationPermit(true);
                        webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE);
    
                        webView.setWebAgent(new WebAgent() {
                            @Override
                            public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
                                super.onLoadingPage(webView, url, favicon);
                                // Custom processing at the beginning of page loading
                                if (url != urlAddress) {
                                   textWebViewUrl.setText(url);
                                }
    
                            }
    
                            @Override
                            public void onPageLoaded(WebView webView, String url) {
                                super.onPageLoaded(webView, url);
                                // Customized processing after page loading
                            }
    
                            @Override
                            public void onLoadingContent(WebView webView, String url) {
                                super.onLoadingContent(webView, url);
                                // Custom processing when loading resources
                            }
    
                            @Override
                            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                                super.onError(webView, request, error);
                                // Custom processing when an error occurs
                            }
                        });
                        webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) {
                            @Override
                            public void onTitleUpdated(WebView webView, String title) {
                                super.onTitleUpdated(webView, title);
                                // Custom processing when Title Changes
                            }
    
                            @Override
                            public void onProgressUpdated(WebView webView, int newProgress) {
                                super.onProgressUpdated(webView, newProgress);
                                if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) {
                                    otherWebViewProgressBar.setVisibility(Component.VISIBLE);
                                    otherWebViewProgressBar.setProgressValue(newProgress);
                                } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) {
                                    otherWebViewProgressBar.setVisibility(Component.HIDE);
                                }
                                // Custom processing when loading progress change
                            }
                        });
                    }
                    break;
                    case ResourceTable.Id_button_webview_back: {
                        if (webView.getNavigator().canGoBack()) {
                            webView.getNavigator().goBack();
                        }
                    }
                    break;
                    case ResourceTable.Id_button_webview_refresh: {
                        webView.reload();
                    }
                    break;
                    case ResourceTable.Id_button_webview_forward: {
                        if (webView.getNavigator().canGoForward()) {
                            webView.getNavigator().goForward();
                        }
                    }
                    break;
                    default: {
                        System.out.println("No pages selected");
                    }
                    break;
                }
            }
        };
    
        /**
         * @Author JavaAIer
         * @Description :
         * @Date: 2021/4/16 14:46
         * * @param intent
         */
        @Override
    
        public void onStart(Intent intent) {
            super.onStart(intent);
            super.setUIContent(ResourceTable.Layout_ability_simple_web_view);
            otherWebViewProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_other_webView_progressBar);
            textWebViewUrl = (TextField) findComponentById(ResourceTable.Id_text_webView_Url);
            buttonWebViewSurf = (Button) findComponentById(ResourceTable.Id_button_webview_surf);
            buttonWebViewSurf.setClickedListener(clickedListener);
            buttonWebViewBack = (Button) findComponentById(ResourceTable.Id_button_webview_back);
            buttonWebViewBack.setClickedListener(clickedListener);
            buttonWebViewRefresh = (Button) findComponentById(ResourceTable.Id_button_webview_refresh);
            buttonWebViewRefresh.setClickedListener(clickedListener);
            buttonWebViewForward = (Button) findComponentById(ResourceTable.Id_button_webview_forward);
            buttonWebViewForward.setClickedListener(clickedListener);
            webView = (WebView) findComponentById(ResourceTable.Id_webview_webview_webview);
    
    
        }
    
        @Override
        public void onActive() {
            super.onActive();
        }
    
        @Override
        public void onForeground(Intent intent) {
            super.onForeground(intent);
        }
    }
    /*
    * This section of Kawaii meow is in config JSON is used. I find it makes no difference whether it is used or not
    * https://blog.csdn.net/qq_33259323/article/details/115596296
    *  "default": {
          "network": {
            "cleartextTraffic": true,
            "securityConfig": {
              "domainSettings": {
                "cleartextPermitted": true,
                "domains": [
                  {
                    "subdomains": true,
                    "name": "www.harmonyos.com"
                  }
                ]
              }
            }
          }
        }
    *
    * */
    
     
 

 
- config.json
 
   ``` json
   {
     "app": {
       "bundleName": "com.javaaier.family.huawei",
       "vendor": "javaaier",
       "version": {
         "code": 1,
         "name": "1.0"
       },
       "apiVersion": {
         "compatible": 5,
         "target": 5,
         "releaseType": "Beta1"
       }
     },
     "deviceConfig": {
   
     },
     "module": {
       "package": "com.javaaier.family.huawei",
       "name": ".MyApplication",
       "deviceType": [
         "phone"
       ],
       "distro": {
         "deliveryWithInstall": true,
         "moduleName": "entry",
         "moduleType": "entry"
       },
       "abilities": [
         {
           "skills": [
             {
               "entities": [
                 "entity.system.home"
               ],
               "actions": [
                 "action.system.home"
               ]
             }
           ],
           "orientation": "unspecified",
           "name": "com.javaaier.family.huawei.MainAbility",
           "icon": "$media:icon",
           "description": "$string:mainability_description",
           "label": "$string:app_name",
           "type": "page",
           "launchType": "standard"
         },
         {
           "orientation": "unspecified",
           "name": "com.javaaier.family.huawei.SimpleWebViewAbility",
           "icon": "$media:icon",
           "description": "$string:simplewebviewability_description",
           "label": "$string:app_name",
           "type": "page",
           "launchType": "standard"
         }
       ],
       "reqPermissions": [
         {
           "name": "ohos.permission.INTERNET"
         }
       ]
     }
   }

Author: AI Ji

For more information, please visit the Hongmeng community jointly built by 51CTO and Huawei: https://harmonyos.51cto.com#kyzg

Topics: Java AI harmonyos