“This is the 39th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

What is a Webview

In fact, many apps now have built-in Web pages, such as wechat and Taobao. In Android is the use of WebView this component. WebView is a webKit-based control that presents web pages.

Hongmeng is no exception, also through WebView to provide the ability to integrate Web pages in the application.

Function:

  • Display and render Web pages
  • Layout directly using HTML files (on the Web or in local resources)
  • Can be interactively called with JavaScript

The WebView supports access to web pages, such as the HarmonyOS app development website in this case, and of course readers can go to any page they want.

Use the WebView

If we want to load remote web pages, we need to add network support. Write the following code in config.json:

  "module": {
    "package": "com.yuzhou1su.webviewdemo"."name": ".MyApplication"."mainAbility": "com.yuzhou1su.webviewdemo.MainAbility"."deviceType": [
      "phone"."tv"."tablet"]."reqPermissions": [{"name": "ohos.permission.INTERNET"	// Add network permissions}].Copy the code

Create a WebView in layout ability_main.xml

In the “slice/MainAbilitySlice. Java file through the webview. Load (String url) method to access a specific Web page, through the WebConfig class behavior of webview component configuration, the code is as follows:

package com.yuzhou1su.webviewdemo.slice;

import com.yuzhou1su.webviewdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.JsMessageResult;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class MainAbilitySlice extends AbilitySlice {

    private static final String URL_LOCAL = "dataability://com.yuzhou1su.webviewdemo.DataAbility/resources/rawfile/BingDwenDwen.html";
    private static final String JS_NAME = "JsCallJava";
    private WebView webview;
    private TextField urlTextField;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    private void initView(a) {
        webview = (WebView) findComponentById(ResourceTable.Id_webview);
        webview.getWebConfig().setDataAbilityPermit(true);  // Set webView support to open local files
        urlTextField = (TextField) findComponentById(ResourceTable.Id_textField);
        initButton();
        configWebView();
    }

    private void configWebView(a) {
        WebConfig webConfig = webview.getWebConfig();

        // Whether Javascript is supported. The default value is false
        webConfig.setJavaScriptPermit(true);
        webview.setWebAgent(new WebAgent() {
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                if (request == null || request.getRequestUrl() == null) {
                    return false;
                }
                String url = request.getRequestUrl().toString();
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    webView.load(url);
                    return false;
                } else {
                    return super.isNeedLoadUrl(webView, request); }}}); webview.setBrowserAgent(new BrowserAgent(this) {
            @Override
            public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
                if (isAlert) {
                    new ToastDialog(getApplicationContext()).setText(message).setAlignment(LayoutAlignment.CENTER).show();
                    result.confirm();
                    return true;
                } else {
                    return super.onJsMessageShow(webView, url, message, isAlert, result); }}});// Configure the processing of messages sent by JS
        webview.addJsCallback(JS_NAME, str -> {
            // Process the received Js message
            new ToastDialog(this).setText(str).setAlignment(LayoutAlignment.CENTER).show();

            // return to Js
            return "Js Call Java Success";
        });
    }

    private void initButton(a) {
        initLoadUrlButton();
        initLoadLocalUrlButton();
    }


    private void initLoadLocalUrlButton(a) {
        Button loadLocalUrlButton = (Button) findComponentById(ResourceTable.Id_load_local_url);
        loadLocalUrlButton.setClickedListener(component -> {
            webview.load(URL_LOCAL);
        });
    }

    private void initLoadUrlButton(a) {
        Button loadUrlButton = (Button) findComponentById(ResourceTable.Id_loadUrl);
        loadUrlButton.setClickedListener(component -> {
            webview.load(urlTextField.getText());
        });
    }

    @Override
    public void onActive(a) {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent); }}Copy the code

Write the following code in background_ability_main.xml:


      
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <solid
        ohos:color="#F8F1EAEA"/>
</shape>
Copy the code

Write the following code in background_button.xml:


      
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="20vp"/>
    <solid
        ohos:color="#FF46F5C3"/>
</shape>
Copy the code

The WebView reads the local page

Place your local HTML file in the “resources/rawfile/” directory and name it bingdwendwen.html for this tutorial. In HarmonyOS, the WebView accesses the local Web file using DataAbility, so create the DataAbility. Java file and write the following code:

package com.yuzhou1su.webviewdemo;

import java.io.FileNotFoundException;
import java.io.IOException;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.global.resource.RawFileDescriptor;
import ohos.utils.net.Uri;

public class DataAbility extends Ability {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
    }

    @Override
    public RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {
        if (uri == null) {
            return super.openRawFile(uri, mode);
        }
        String path = uri.getEncodedPath();
        final int splitIndex = path.indexOf('/'.1);
        final String providerName = Uri.decode(path.substring(1, splitIndex));
        String rawFilePath = Uri.decode(path.substring(splitIndex + 1));
        RawFileDescriptor rawFileDescriptor = null;
        try {
            rawFileDescriptor = getResourceManager().getRawFileEntry(rawFilePath).openRawFileDescriptor();
        } catch (IOException e) {
            // Handle exceptions
        }
        returnrawFileDescriptor; }}Copy the code

Then in the “entry/SRC/main/config. The json” in complete DataAbility statement, the code is as follows:

{
        "name": "com.yuzhou1su.webviewdemo.DataAbility"."type": "data"."uri": "dataability://com.yuzhou1su.webviewdemo.DataAbility"
      }
Copy the code

So far, the entire config.json file looks like this:

{
  "app": {
    "bundleName": "com.yuzhou1su.webviewdemo"."vendor": "yuzhou1su"."version": {
      "code": 1000000."name": "1.0.0"}},"deviceConfig": {},
  "module": {
    "package": "com.yuzhou1su.webviewdemo"."name": ".MyApplication"."mainAbility": "com.yuzhou1su.webviewdemo.MainAbility"."deviceType": [
      "phone"."tv"."tablet"]."reqPermissions": [{"name": "ohos.permission.INTERNET"}]."distro": {
      "deliveryWithInstall": true."moduleName": "entry"."moduleType": "entry"."installationFree": true
    },
    "abilities": [{"skills": [{"entities": [
              "entity.system.home"]."actions": [
              "action.system.home"]}],"orientation": "unspecified"."name": "com.yuzhou1su.webviewdemo.MainAbility"."icon": "$media:icon"."description": "$string:mainability_description"."label": "$string:entry_MainAbility"."type": "page"."launchType": "standard"
      },
      {
        "name": "com.yuzhou1su.webviewdemo.DataAbility"."type": "data"."uri": "dataability://com.yuzhou1su.webviewdemo.DataAbility"}}}]Copy the code

Then in the “slice/MainAbilitySlice. Java” statement need to access the file path, through the webview. Load (String url) method to load the local Web page, The ability of WebView to access DataAbility can be configured using an object of the WebConfig class, with the following example code:

private static final String URL_LOCAL = "dataability://com.yuzhou1su.webviewdemo.DataAbility/resources/rawfile/BingDwenDwen.html";
    private static final String JS_NAME = "JsCallJava";
    private WebView webview;
    private TextField urlTextField;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }
Copy the code

The code structure is as follows

Then run a MataPad Pro and execute our code:

Click to open the online webpage, you can see the official website of Hongmeng Development:

conclusion

Embedded WebViews always have a place in App development. It can reuse Android, iOS and the Web at a low cost. — Meituan Technical team

So far, we’ve been able to access remote web pages and local HTML through a WebView, but this is just a minor effort.

If you still want to explore WebView, you can explore it yourself. If you are interested in making an in-app browser after reading my article, then I have done my job.

Hope more friends to join the team of Hongmeng development, the next article, we see you!

References:

  • Official WebView case