使用鸿蒙WebView创建简单浏览器 step 1

系统
文章由鸿蒙社区产出,想要了解更多内容请前往:51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com

[[394423]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

1. 打开官网,找到WebView的文档(模拟器不支持)

鸿蒙webview的开发指南(原始链接,方便大家识别并点击):https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158

2. 创建一个Page Ability,把基本布局弄好

下面是代码

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:height="match_parent" 
  5.     ohos:width="match_parent" 
  6.     ohos:orientation="vertical"
  7.     <DirectionalLayout 
  8.         ohos:height="30vp" 
  9.         ohos:width="match_parent" 
  10.         ohos:orientation="horizontal"
  11.         <TextField 
  12.             ohos:id="$+id:text_webView_Url" 
  13.             ohos:height="match_content" 
  14.             ohos:width="match_parent" 
  15.             ohos:background_element="$graphic:background_ability_simple_web_view" 
  16.             ohos:focus_border_enable="true" 
  17.             ohos:hint="请输入网址" 
  18.             ohos:max_text_lines="1" 
  19.             ohos:multiple_lines="false" 
  20.             ohos:scrollable="true" 
  21.             ohos:text="www.harmonyos.com" 
  22.             ohos:text_size="50" 
  23.             ohos:weight="1" 
  24.             /> 
  25.         <Button 
  26.             ohos:id="$+id:button_webview_Surf" 
  27.             ohos:height="match_content" 
  28.             ohos:width="60vp" 
  29.             ohos:background_element="$graphic:button_element" 
  30.             ohos:text="跳转" 
  31.             ohos:text_size="50"/> 
  32.     </DirectionalLayout> 
  33.     <ProgressBar 
  34.         ohos:id="$+id:other_webView_progressBar" 
  35.         ohos:height="10vp" 
  36.         ohos:width="match_parent" 
  37.         ohos:visibility="hide"
  38.     </ProgressBar> 
  39.     <ohos.agp.components.webengine.WebView 
  40.         ohos:id="$+id:webview_webview_webview" 
  41.         ohos:height="match_parent" 
  42.         ohos:width="match_parent" 
  43.         ohos:weight="1"
  44.     </ohos.agp.components.webengine.WebView> 
  45.     <DirectionalLayout 
  46.         ohos:height="30vp" 
  47.         ohos:width="match_parent" 
  48.         ohos:orientation="horizontal"
  49.         <DirectionalLayout 
  50.             ohos:height="match_content" 
  51.             ohos:width="match_parent" 
  52.             ohos:orientation="horizontal" 
  53.             ohos:weight="1"
  54.             <Button 
  55.                 ohos:id="$+id:button_webview_back" 
  56.                 ohos:height="match_content" 
  57.                 ohos:width="match_parent" 
  58.                 ohos:background_element="$graphic:button_element" 
  59.                 ohos:layout_alignment="horizontal_center" 
  60.                 ohos:text="向后" 
  61.                 ohos:text_size="50" 
  62.                 > 
  63.             </Button> 
  64.         </DirectionalLayout> 
  65.         <DirectionalLayout 
  66.             ohos:height="match_content" 
  67.             ohos:width="match_parent" 
  68.             ohos:orientation="horizontal" 
  69.             ohos:weight="1"
  70.             <Button 
  71.                 ohos:id="$+id:button_webview_refresh" 
  72.                 ohos:height="match_content" 
  73.                 ohos:width="match_parent" 
  74.                 ohos:background_element="$graphic:button_element" 
  75.                 ohos:layout_alignment="horizontal_center" 
  76.                 ohos:text="刷新" 
  77.                 ohos:text_size="50"
  78.             </Button> 
  79.         </DirectionalLayout> 
  80.         <DirectionalLayout 
  81.             ohos:height="match_content" 
  82.             ohos:width="match_parent" 
  83.             ohos:orientation="horizontal" 
  84.             ohos:weight="1"
  85.             <Button 
  86.                 ohos:id="$+id:button_webview_forward" 
  87.                 ohos:height="match_content" 
  88.                 ohos:width="match_parent" 
  89.                 ohos:background_element="$graphic:button_element" 
  90.                 ohos:layout_alignment="horizontal_center" 
  91.                 ohos:text="向前" 
  92.                 ohos:text_size="50"
  93.             </Button> 
  94.         </DirectionalLayout> 
  95.     </DirectionalLayout> 
  96. </DirectionalLayout> 

3.把基本的按钮事件弄好

代码

  1. Component.ClickedListener clickedListener = new Component.ClickedListener() { 
  2.      @Override 
  3.      public void onClick(Component component) { 
  4.          int componentId = component.getId(); 
  5.          switch (componentId) { 
  6.              case ResourceTable.Id_button_webview_Surf: { 
  7.                  urlAddress = textWebViewUrl.getText(); 
  8.                  if (urlAddress.isEmpty()) { 
  9.                      return
  10.                  } 
  11.                  if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) { 
  12.                      urlAddress = FinalValue.URL_HTTPS + urlAddress; 
  13.                  } 
  14.                  webView.load(urlAddress); 
  15.  
  16.                  
  17.              } 
  18.              break; 
  19.              case ResourceTable.Id_button_webview_back: { 
  20.                  if (webView.getNavigator().canGoBack()) { 
  21.                      webView.getNavigator().goBack(); 
  22.                  } 
  23.              } 
  24.              break; 
  25.              case ResourceTable.Id_button_webview_refresh: { 
  26.                  webView.reload(); 
  27.              } 
  28.              break; 
  29.              case ResourceTable.Id_button_webview_forward: { 
  30.                  if (webView.getNavigator().canGoForward()) { 
  31.                      webView.getNavigator().goForward(); 
  32.                  } 
  33.              } 
  34.              break; 
  35.              default: { 
  36.                  System.out.println("没有选择任何的页面"); 
  37.              } 
  38.              break; 
  39.          } 
  40.      } 
  41.  }; 

4.把WebView照文档上面的要求弄好

没啥好说的,就是规定.我加在了调用load方法打开网址那行代码后面,我还弄了一个跟进度条关联的功能

  1. //允许javascript交互 
  2.  
  3.                   WebConfig webConfig = webView.getWebConfig(); 
  4.                   webConfig.setDataAbilityPermit(true); 
  5.                   webConfig.setJavaScriptPermit(true); 
  6.                   webConfig.setLoadsImagesPermit(true); 
  7.                   webConfig.setMediaAutoReplay(true); 
  8.                   webConfig.setLocationPermit(true); 
  9.                   webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE); 
  10.  
  11.                   webView.setWebAgent(new WebAgent() { 
  12.                       @Override 
  13.                       public void onLoadingPage(WebView webView, String url, PixelMap favicon) { 
  14.                           super.onLoadingPage(webView, url, favicon); 
  15.                           // 这儿我加了一个更新网址文本框中新页面url的功能 
  16.                           if (url != urlAddress) { 
  17.                              textWebViewUrl.setText(url); 
  18.                           } 
  19.  
  20.                       } 
  21.  
  22.                       @Override 
  23.                       public void onPageLoaded(WebView webView, String url) { 
  24.                           super.onPageLoaded(webView, url); 
  25.                           // 页面加载结束后自定义处理 
  26.                       } 
  27.  
  28.                       @Override 
  29.                       public void onLoadingContent(WebView webView, String url) { 
  30.                           super.onLoadingContent(webView, url); 
  31.                           // 加载资源时自定义处理 
  32.                       } 
  33.  
  34.                       @Override 
  35.                       public void onError(WebView webView, ResourceRequest request, ResourceError error) { 
  36.                           super.onError(webView, request, error); 
  37.                           // 发生错误时自定义处理 
  38.                       } 
  39.                   }); 
  40.                   webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) { 
  41.                       @Override 
  42.                       public void onTitleUpdated(WebView webView, String title) { 
  43.                           super.onTitleUpdated(webView, title); 
  44.                           // 标题变更时自定义处理 
  45.                       } 
  46.  
  47.                       @Override 
  48.                       public void onProgressUpdated(WebView webView, int newProgress) { 
  49.                           super.onProgressUpdated(webView, newProgress); 
  50.                           if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) { 
  51.                               otherWebViewProgressBar.setVisibility(Component.VISIBLE); 
  52.                               otherWebViewProgressBar.setProgressValue(newProgress); 
  53.                           } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) { 
  54.                               otherWebViewProgressBar.setVisibility(Component.HIDE); 
  55.                           } 
  56.                           // 加载进度变更时自定义处理 
  57.                       } 
  58.                   }); 

5.完事?or完了还有事?

从上面拷代码的话,估计完事了.但是,我是用的回忆,但是代码却没有回退,所以我还是有必要在这儿把步骤中的问题说一说,方便不拷代码的同学也能跑出一个界面.主要体现如下:

1.权限配置,不多说

  1. "reqPermissions": [ 
  2.      { 
  3.        "name""ohos.permission.INTERNET" 
  4.      } 
  5.    ] 

2.xml中的WebView要带包名

  1. <ohos.agp.components.webengine.WebView 
  2.       ohos:id="$+id:webview_webview_webview" 
  3.       ohos:height="match_parent" 
  4.       ohos:width="match_parent" 
  5.       ohos:weight="1"
  6.   </ohos.agp.components.webengine.WebView> 

不按上面包名写的话:

  • 真机运行后没有WebView的界面.哪怕weight=1,也不行
  • 点击跳转按钮后,PageAbility会闪退,回到首屏(调用它的页面)

完事效果:https://www.bilibili.com/video/BV1tK4y1o7Hz/

6.完整代码

  • 布局

          序号为2的步骤中贴全了

  • 按钮背景
  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  3.        ohos:shape="rectangle"
  4.     <corners 
  5.         ohos:radius="20"/> 
  6.     <solid 
  7.         ohos:color="#70dbdb"/> 
  8. </shape> 
  • java代码
  1. package com.javaaier.family.huawei.slice; 
  2.  
  3. import com.javaaier.family.huawei.ResourceTable; 
  4. import com.javaaier.family.huawei.common.FinalValue; 
  5. import ohos.aafwk.ability.AbilitySlice; 
  6. import ohos.aafwk.content.Intent; 
  7. import ohos.agp.components.*; 
  8. import ohos.agp.components.webengine.*; 
  9. import ohos.media.image.PixelMap; 
  10.  
  11. /** 
  12.  * @Author JavaAIer 
  13.  * @Description : webview控件例子1:用于简单的测试webview的用法 <br/> 
  14.  * 001 简单webview示例 
  15.  * @Date: 2021/4/16 
  16.  */ 
  17. public class SimpleWebViewAbilitySlice extends AbilitySlice { 
  18.     String urlAddress; 
  19.  
  20.  
  21.     ProgressBar otherWebViewProgressBar; 
  22.     TextField textWebViewUrl; 
  23.     Button buttonWebViewSurf, buttonWebViewBack, buttonWebViewRefresh, buttonWebViewForward; 
  24.     WebView webView; 
  25.  
  26.     Component.ClickedListener clickedListener = new Component.ClickedListener() { 
  27.         @Override 
  28.         public void onClick(Component component) { 
  29.             int componentId = component.getId(); 
  30.             switch (componentId) { 
  31.                 case ResourceTable.Id_button_webview_Surf: { 
  32.                     urlAddress = textWebViewUrl.getText(); 
  33.                     if (urlAddress.isEmpty()) { 
  34.                         return
  35.                     } 
  36.                     if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) { 
  37.                         urlAddress = FinalValue.URL_HTTPS + urlAddress; 
  38.                     } 
  39.                     webView.load(urlAddress); 
  40.  
  41.                     //允许javascript交互 
  42.  
  43.                     WebConfig webConfig = webView.getWebConfig(); 
  44.                     webConfig.setDataAbilityPermit(true); 
  45.                     webConfig.setJavaScriptPermit(true); 
  46.                     webConfig.setLoadsImagesPermit(true); 
  47.                     webConfig.setMediaAutoReplay(true); 
  48.                     webConfig.setLocationPermit(true); 
  49.                     webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE); 
  50.  
  51.                     webView.setWebAgent(new WebAgent() { 
  52.                         @Override 
  53.                         public void onLoadingPage(WebView webView, String url, PixelMap favicon) { 
  54.                             super.onLoadingPage(webView, url, favicon); 
  55.                             // 页面开始加载时自定义处理 
  56.                             if (url != urlAddress) { 
  57.                                textWebViewUrl.setText(url); 
  58.                             } 
  59.  
  60.                         } 
  61.  
  62.                         @Override 
  63.                         public void onPageLoaded(WebView webView, String url) { 
  64.                             super.onPageLoaded(webView, url); 
  65.                             // 页面加载结束后自定义处理 
  66.                         } 
  67.  
  68.                         @Override 
  69.                         public void onLoadingContent(WebView webView, String url) { 
  70.                             super.onLoadingContent(webView, url); 
  71.                             // 加载资源时自定义处理 
  72.                         } 
  73.  
  74.                         @Override 
  75.                         public void onError(WebView webView, ResourceRequest request, ResourceError error) { 
  76.                             super.onError(webView, request, error); 
  77.                             // 发生错误时自定义处理 
  78.                         } 
  79.                     }); 
  80.                     webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) { 
  81.                         @Override 
  82.                         public void onTitleUpdated(WebView webView, String title) { 
  83.                             super.onTitleUpdated(webView, title); 
  84.                             // 标题变更时自定义处理 
  85.                         } 
  86.  
  87.                         @Override 
  88.                         public void onProgressUpdated(WebView webView, int newProgress) { 
  89.                             super.onProgressUpdated(webView, newProgress); 
  90.                             if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) { 
  91.                                 otherWebViewProgressBar.setVisibility(Component.VISIBLE); 
  92.                                 otherWebViewProgressBar.setProgressValue(newProgress); 
  93.                             } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) { 
  94.                                 otherWebViewProgressBar.setVisibility(Component.HIDE); 
  95.                             } 
  96.                             // 加载进度变更时自定义处理 
  97.                         } 
  98.                     }); 
  99.                 } 
  100.                 break; 
  101.                 case ResourceTable.Id_button_webview_back: { 
  102.                     if (webView.getNavigator().canGoBack()) { 
  103.                         webView.getNavigator().goBack(); 
  104.                     } 
  105.                 } 
  106.                 break; 
  107.                 case ResourceTable.Id_button_webview_refresh: { 
  108.                     webView.reload(); 
  109.                 } 
  110.                 break; 
  111.                 case ResourceTable.Id_button_webview_forward: { 
  112.                     if (webView.getNavigator().canGoForward()) { 
  113.                         webView.getNavigator().goForward(); 
  114.                     } 
  115.                 } 
  116.                 break; 
  117.                 default: { 
  118.                     System.out.println("没有选择任何的页面"); 
  119.                 } 
  120.                 break; 
  121.             } 
  122.         } 
  123.     }; 
  124.  
  125.     /** 
  126.      * @Author JavaAIer 
  127.      * @Description : 
  128.      * @Date: 2021/4/16 14:46 
  129.      * * @param intent 
  130.      */ 
  131.     @Override 
  132.  
  133.     public void onStart(Intent intent) { 
  134.         super.onStart(intent); 
  135.         super.setUIContent(ResourceTable.Layout_ability_simple_web_view); 
  136.         otherWebViewProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_other_webView_progressBar); 
  137.         textWebViewUrl = (TextField) findComponentById(ResourceTable.Id_text_webView_Url); 
  138.         buttonWebViewSurf = (Button) findComponentById(ResourceTable.Id_button_webview_Surf); 
  139.         buttonWebViewSurf.setClickedListener(clickedListener); 
  140.         buttonWebViewBack = (Button) findComponentById(ResourceTable.Id_button_webview_back); 
  141.         buttonWebViewBack.setClickedListener(clickedListener); 
  142.         buttonWebViewRefresh = (Button) findComponentById(ResourceTable.Id_button_webview_refresh); 
  143.         buttonWebViewRefresh.setClickedListener(clickedListener); 
  144.         buttonWebViewForward = (Button) findComponentById(ResourceTable.Id_button_webview_forward); 
  145.         buttonWebViewForward.setClickedListener(clickedListener); 
  146.         webView = (WebView) findComponentById(ResourceTable.Id_webview_webview_webview); 
  147.  
  148.  
  149.     } 
  150.  
  151.     @Override 
  152.     public void onActive() { 
  153.         super.onActive(); 
  154.     } 
  155.  
  156.     @Override 
  157.     public void onForeground(Intent intent) { 
  158.         super.onForeground(intent); 
  159.     } 
  160. /* 
  161. * 这一截卡哇伊大喵在config.json用了,我发现用不用没啥区别啊 
  162. * https://blog.csdn.net/qq_33259323/article/details/115596296 
  163. *  "default": { 
  164.       "network": { 
  165.         "cleartextTraffic"true
  166.         "securityConfig": { 
  167.           "domainSettings": { 
  168.             "cleartextPermitted"true
  169.             "domains": [ 
  170.               { 
  171.                 "subdomains"true
  172.                 "name""www.harmonyos.com" 
  173.               } 
  174.             ] 
  175.           } 
  176.         } 
  177.       } 
  178.     } 
  179. * */ 
  1.    
  2. - config.json  
  3.    
  4.    ``` json  
  5.    {  
  6.      "app": {  
  7.        "bundleName""com.javaaier.family.huawei",  
  8.        "vendor""javaaier",  
  9.        "version": {  
  10.          "code": 1,  
  11.          "name""1.0"  
  12.        },  
  13.        "apiVersion": {  
  14.          "compatible": 5,  
  15.          "target": 5,  
  16.          "releaseType""Beta1"  
  17.        }  
  18.      },  
  19.      "deviceConfig": {  
  20.      
  21.      },  
  22.      "module": {  
  23.        "package""com.javaaier.family.huawei",  
  24.        "name"".MyApplication",  
  25.        "deviceType": [  
  26.          "phone"  
  27.        ],  
  28.        "distro": {  
  29.          "deliveryWithInstall"true,  
  30.          "moduleName""entry",  
  31.          "moduleType""entry"  
  32.        },  
  33.        "abilities": [  
  34.          {  
  35.            "skills": [  
  36.              {  
  37.                "entities": [  
  38.                  "entity.system.home"  
  39.                ],  
  40.                "actions": [  
  41.                  "action.system.home"  
  42.                ]  
  43.              }  
  44.            ],  
  45.            "orientation""unspecified",  
  46.            "name""com.javaaier.family.huawei.MainAbility",  
  47.            "icon""$media:icon",  
  48.            "description""$string:mainability_description",  
  49.            "label""$string:app_name",  
  50.            "type""page",  
  51.            "launchType""standard"  
  52.          },  
  53.          {  
  54.            "orientation""unspecified",  
  55.            "name""com.javaaier.family.huawei.SimpleWebViewAbility",  
  56.            "icon""$media:icon",  
  57.            "description""$string:simplewebviewability_description",  
  58.            "label""$string:app_name",  
  59.            "type""page",  
  60.            "launchType""standard"  
  61.          }  
  62.        ],  
  63.        "reqPermissions": [  
  64.          {  
  65.            "name""ohos.permission.INTERNET"  
  66.          }  
  67.        ]  
  68.      }  
  69.    }  

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2009-08-31 14:54:35

C#对象浏览器

2012-03-20 11:31:58

移动浏览器

2012-03-19 17:25:22

2012-03-20 11:41:18

海豚浏览器

2012-03-20 11:07:08

2012-06-21 15:38:02

猎豹浏览器

2010-04-05 21:57:14

Netscape浏览器

2012-03-19 17:17:00

移动浏览器欧朋

2012-03-20 11:22:02

QQ手机浏览器

2018-12-06 09:00:00

LinuxWeb浏览器

2012-03-20 11:35:32

傲游手机浏览器

2012-06-04 10:35:55

FirefoxChrome浏览器

2020-09-09 07:00:00

TensorFlow神经网络人工智能

2013-04-25 11:14:22

IE浏览器

2015-01-23 16:32:52

2012-03-06 09:18:38

Silverlight

2009-03-19 09:21:01

Mozilla移动浏览器Fennec

2010-12-21 10:11:35

手机浏览器

2012-08-23 14:56:46

浏览器

2015-06-11 14:05:46

QQ浏览器
点赞
收藏

51CTO技术栈公众号