1

HarmonyOS - JavaUI 框架之使用WebView加载本地H5页面

 1 year ago
source link: https://os.51cto.com/article/707713.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaUI 框架之使用WebView加载本地H5页面-51CTO.COM

HarmonyOS - JavaUI 框架之使用WebView加载本地H5页面
作者:陈忠蔚 2022-04-28 15:38:42
WebView 是一个基于 webkit 引擎、展现 web 页面的控件,可以显示和渲染web页面,相当于应用中的浏览器,可以加载网络上或应用本地的HTML文件。

d2acb1b31e967b4ac380723da600aa2eed0cf6.png

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

​51CTO OpenHarmony技术社区​

​https://ost.51cto.com​

现在应用开发中都不可避免的需要加载一些H5页面。HarmonyOS应用通过 WebView 来提供应用中集成H5页面的能力。在HarmonyOS应用中,出于安全考虑,WebView不支持直接通过File协议加载资源文件或本地文件,所以不能直接通过文件的存放路径,加载本地H5页面,下面介绍一下在HarmonyOS应用中,如何实现加载本地H5页面。

WebView使用介绍

WebView 是一个基于 webkit 引擎、展现 web 页面的控件,可以显示和渲染web页面,相当于应用中的浏览器,可以加载网络上或应用本地的HTML文件。

WebView的能力:

  • 显示和渲染 Web 页面。
  • 直接使用 HTML文件(网络上或本地 resources 中)作布局。
  • 可和 JavaScript 交互调用。

效果展示:

a47e9b4787672e5d943252972eb68aa4b14947.png

实现步骤:

1. 首先在resources目录下创建rawfile文件夹,该目录下的资源会打包进应用内。

d10dcde318d3d6a5252306ff03750e23484b4d.png

2.将H5页面放到entry/src/main/resources/rawfile文件夹下。

05f3529631301e9c3e073247fe0421433cc3e2.png

3.WebView 要访问本地 Web 文件,需要通过DataAbility 的方式进行访问,这里创建一个 WebAbility.java 文件。

在WebAbility中进行本地资源文件的解析,重写 RawFileDescriptor(),获取到我们解析到的RawFileDescriptor对象,RawFileDescriptor可以看作是我们访问HarmonyOS应用本地资源文件的入口,通过该入口可以将我们的H5页面加载到WebView控件上。

注意:private static final String ENTRY_PATH_PREFIX = “entry/resources” 这里将 “entry” 替换成自己对应modul的路径。

public class WebAbility extends Ability {
    private static final String PLACEHOLDER_RAW_FILE = "/rawfile/";
    private static final String PLACEHOLDER_LOCAL_FILE = "/local/";
    private static final String ENTRY_PATH_PREFIX = "entry/resources";
      @Override
    public RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {
        final int splitChar = '/';
        if (uri == null) {
            throw new FileNotFoundException("Invalid Uri");
        }
        // 获取uri对应的资源路径 例如:com.example.dataability/entry/resources/rawfile/
        String path = uri.getEncodedPath();
        final int splitIndex = path.indexOf(splitChar, 1);
        if (splitIndex < 0) {
            throw new FileNotFoundException("Invalid Uri " + uri);
        }
        // 处理不同路径下的资源文件
        String targetPath = path.substring(splitIndex);
        if (targetPath.startsWith(PLACEHOLDER_RAW_FILE)) {
            // 打开entry/resources/rawfile目录下的资源
            try {
                return getResourceManager().getRawFileEntry(ENTRY_PATH_PREFIX + targetPath).openRawFileDescriptor();
            } catch (IOException e) {
                throw new FileNotFoundException("Not found support raw file at " + uri);
            }
        } else if (targetPath.startsWith(PLACEHOLDER_LOCAL_FILE)) {
            // 打开手机本地存储目录下的资源
            File file = new File(getContext().getFilesDir(), targetPath.replace(PLACEHOLDER_LOCAL_FILE, ""));
            if (!file.exists()) {
                throw new FileNotFoundException("Not found support local file at " + uri);
            }
            return getRawFileDescriptor(file, uri);
        } else {
            throw new FileNotFoundException("Not found support file at " + uri);
        }
    }
    //获取手机本地存储目录下文件资源的访问入口
    private RawFileDescriptor getRawFileDescriptor(File file, Uri uri) throws FileNotFoundException {
        try {
            final FileDescriptor fileDescriptor = new FileInputStream(file).getFD();
            return new RawFileDescriptor() {
                @Override
                public FileDescriptor getFileDescriptor() {
                    return fileDescriptor;
                }
                @Override
                public long getFileSize() {
                    return -1;
                }
                @Override
                public long getStartPosition() {
                    return 0;
                }
                @Override
                public void close() throws IOException {
                }
            };
        } catch (IOException e) {
            throw new FileNotFoundException("Not found support local file at " + uri);
        }
    }

4.然后在 “entry/src/main/config.json” 中完成 WebAbility 的声明,代码如下:

 {
        "name": "com.example.webdemo.WebAbility",
        "type": "data",
        "uri": "dataability://com.example.webdemo.dataability"
 },

找到config.json的对应的module,在abilities节点中添加以上代码,具体位置如下:

"abilities": [
       {
        "name": "com.example.webdemo.WebAbility",
        "type": "data",
        "uri": "dataability://com.example.webdemo.dataability"
      },
      {
        "visible": true,
        "name": "com.example.webdemo.MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description",
        "formsEnabled": true,
        "label": "$string:entry_MainAbility",
        "type": "page",
      }
    ],
......

在abilities中声明的 uri 的值便是webview加载的路径,在WebAbility里面进行了资源文件的解析,当路径指向WebAbility时,H5页面就可以在WebAbility上显示了。

5.创建 WebView 并加载本地页面。

在MainAbility的onStart()中创建WebView,并配置支持访问Data Ability资源,支持JavaScript,通过webView.load()加载本地H5页面,加载地址为:“dataability://com.example.webdemo.dataability/rawfile/help-center/index.html#/”,“dataability://com.example.webdemo.dataability”是指向解析本地资源文件的Ability,后面拼接加载页面的路径,具体代码如下:

  DirectionalLayout dLayout = new DirectionalLayout(this);
  dLayout.setLayoutConfig(new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT,
                ComponentContainer.LayoutConfig.MATCH_PARENT
        ));
  super.setUIContent(dLayout);
  WebView webView = new WebView(this);
  webView.getWebConfig().setJavaScriptPermit(true);
  webView.getWebConfig().setDataAbilityPermit(true);
  webView.load("dataability://com.example.webdemo.dataability/rawfile/help-center/index.html#/");
  dLayout.addComponent(webView);

实际项目中APP中的H5页面一般都是通过网络获取的,并不需要本地解析资源文件。但是手机断网或者网络不稳定时,可以下载H5页面到本地,通过以上方式使用webview加载本地H5页面,避免出现手机断网或者网络不稳定时页面加载不了的情况。

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

​51CTO OpenHarmony技术社区​

​https://ost.51cto.com​

71eea7105a1cf9982d2996c42d853b97bd50ef.jpg


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK