harmonyos webview范例 原创

发布于 2021-6-11 11:41
浏览
0收藏

鸿蒙系统 WebView app 范例
项目代码:https://gitee.com/hljdrl/harmonyos-app-example-webview

  1. WebView加载在线地址
  2. WebView加载本地网址
  3. WebView加载app内置资源(一)
  4. WebView加载app内置资源(二)

WebAbility

package org.ohos.sample.webview.home;

import com.utalk.kernel.logger.L;
import com.utalk.kernel.util.StringCompat;
import ohos.aafwk.content.Operation;
import ohos.multimodalinput.event.KeyEvent;
import org.ohos.sample.webview.home.slice.WebAbilitySlice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

public class WebAbility extends Ability {

public  static final String KEY_URL="_webview_url";
public static final void start(Ability ability,String url){
    Intent intent = new Intent();
    Operation operation = new Intent.OperationBuilder().withDeviceId("")
            .withBundleName(ability.getBundleName())
            .withAbilityName(WebAbility.class)
            .build();
    intent.setOperation(operation);
    intent.setParam(KEY_URL,url);
    ability.startAbility(intent);
}
private String TAG="WebAbility";
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
    L.i(TAG, StringCompat.string("onKeyDown->keyCode=",keyCode));
    return super.onKeyDown(keyCode, keyEvent);
}

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    super.setMainRoute(WebAbilitySlice.class.getName());
}

}

WebAbilitySlice
package org.ohos.sample.webview.home.slice;

import com.utalk.kernel.logger.L;
import com.utalk.kernel.util.StringCompat;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.multimodalinput.event.KeyEvent;
import org.ohos.sample.cordova.SystemWebViewEngine;
import org.ohos.sample.cordova.WebViewEngine;
import org.ohos.sample.cordova.WebViewInterface;
import org.ohos.sample.webview.ResourceTable;
import org.ohos.sample.webview.home.WebAbility;

import java.util.Optional;

/**
*

  • 加载资源文件 dataability://org.ohos.sample.data.DataAbility
  • final String URL_LOCAL = “dataability://org.ohos.sample.data.DataAbility/resources/rawfile/web/index.html”;
  • webViewEngine.load(URL_LOCAL);
  • 加载资源文件 resources/rawfile/example.html
  • webViewEngine.load(loadUrl);
  • 加载本地文件 /data/data/com.example.dataability/files/example.html
  • webViewEngine.load(“https://example.com/local/example.html”);
  • 加载网址
  • webViewEngine.load(“http://elemefe.github.io/mint-ui/#/”);

*/
public class WebAbilitySlice extends AbilitySlice implements WebViewInterface {

private WebViewEngine webViewEngine;
private String loadUrl;

private WebViewInterface webViewInterface;

// private Component viewLoad;
private Component progressBarLayout;
private ProgressBar mProgressBar;
private String TAG=“WebAbilitySlice”;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
WindowManager.getInstance().getTopWindow().get().setTransparent(true);
super.setUIContent(ResourceTable.Layout_ability_webview);
Optional<Display>
display = DisplayManager.getInstance().getDefaultDisplay(this.getContext());
Point pt = new Point();
display.get().getSize(pt);
WebView mWebView = (WebView) findComponentById(ResourceTable.Id_webview);
progressBarLayout = findComponentById(ResourceTable.Id_webview_load_progress);
mProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_webview_view_progressbar);
L.i(TAG,StringCompat.string(“x=”,pt.getPointXToInt()," y=",pt.getPointYToInt()));

    if(intent.hasParameter(WebAbility.KEY_URL)){
        loadUrl = intent.getStringParam(WebAbility.KEY_URL);
    }else{
        loadUrl="https://example.com/rawfile/web/index.html";
    }
    webViewInterface = this;
    if(webViewEngine==null){
        webViewEngine = new SystemWebViewEngine(getApplicationContext(),webViewInterface);
    }
    webViewEngine.init(mWebView);
    mWebView.load(loadUrl);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent keyEvent) {
    L.i(TAG,StringCompat.string("onKeyUp->keyCode=",keyCode));
    return super.onKeyUp(keyCode, keyEvent);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
    L.i(TAG,StringCompat.string("onKeyDown->keyCode=",keyCode));
    if(keyCode==KeyEvent.KEY_BACK){
        boolean canGoBack = webViewEngine.canGoBack();
        L.i(TAG,StringCompat.string("onKeyDown->WebViewEngine canGoBack=",canGoBack));
        if(canGoBack){
            webViewEngine.goBack();
            return  true;
        }
    }
    return super.onKeyDown(keyCode, keyEvent);
}

@Override
protected void onStop() {
    super.onStop();
    if(webViewEngine!=null){
        webViewEngine.destroy();
    }
}

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

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

@Override
public void showWebViewLoading() {
    L.i(TAG,"showWebViewLoading");
    if(progressBarLayout!=null){
        progressBarLayout.setVisibility(Component.VISIBLE);
    }
}

@Override
public void hideWebViewLoading() {
    L.i(TAG,"hideWebViewLoading");
    if(progressBarLayout!=null){
        progressBarLayout.setVisibility(Component.HIDE);
    }
}

@Override
public void onWebViewPageFinished() {
    L.i(TAG,"onWebViewPageFinished");
}
@Override
public void onWebViewProgressUpdated(int newProgress) {
    L.i(TAG, StringCompat.string("onWebViewProgressUpdated=",newProgress));
    if(mProgressBar!=null){
        mProgressBar.setProgressValue(newProgress);
    }
}

}

WebViewInterface
package org.ohos.sample.cordova;

import ohos.app.Context;

public interface WebViewInterface {

Context getContext();

 void showWebViewLoading();

 void hideWebViewLoading();

 void onWebViewPageFinished();

 void onWebViewProgressUpdated(int newProgress);

}

WebViewEngine

package org.ohos.sample.cordova;

import ohos.agp.components.webengine.WebView;
import ohos.app.Context;

public abstract class WebViewEngine {

private Context mContext;
protected WebViewInterface webViewInterface;
public WebViewEngine(Context context,WebViewInterface webViewInterface){
    mContext = context.getApplicationContext();
    this.webViewInterface = webViewInterface;
}

public final  Context getContext(){
    return mContext;
}
public abstract void init(WebView webView);

public abstract void load(String url);

public abstract boolean canGoBack();

public abstract void goBack();

public abstract void goForward();

public abstract boolean canGoForward();

public abstract void destroy();

}

SystemWebViewEngine
package org.ohos.sample.cordova;

import ohos.agp.components.webengine.Navigator;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;

public class SystemWebViewEngine extends WebViewEngine {

private WebView mWebView;

public SystemWebViewEngine(Context context, WebViewInterface webViewInterface) {
    super(context, webViewInterface);
}

public void init(WebView webView){
    mWebView = webView;
    settingsWebView();
}
private void settingsWebView(){
    WebConfig webConfig = mWebView.getWebConfig();
    webConfig.setJavaScriptPermit(true);
    webConfig.setDataAbilityPermit(true);
    webConfig.setWebStoragePermit(true);
    webConfig.setViewPortFitScreen(true);

// webConfig.setLocationPermit(true);
mWebView.setWebAgent(new SystemWebAgent(webViewInterface));
mWebView.setBrowserAgent(new SystemBrowserAgent(getContext(),webViewInterface));
} @Override
public void load(String url) {
mWebView.load(url);
}

@Override
public boolean canGoBack() {
    Navigator navigator = mWebView.getNavigator();
   return navigator.canGoBack();
}

@Override
public void goBack() {
    Navigator navigator = mWebView.getNavigator();
    if (navigator.canGoBack()) {
        navigator.goBack();
    }
}

@Override
public void goForward() {
    Navigator navigator = mWebView.getNavigator();
    if (navigator.canGoForward()) {
        navigator.goForward();
    }
}

@Override
public boolean canGoForward() {
    Navigator navigator = mWebView.getNavigator();
    if (navigator.canGoForward()) {
        return true;
    }
    return  false;
}

@Override
public void destroy() {
    if(mWebView!=null){
        mWebView.load("about:blank");
    }
}

}

SystemWebAgent
package org.ohos.sample.cordova;

import com.utalk.kernel.logger.L;
import com.utalk.kernel.util.StringCompat;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

public class SystemWebAgent extends WebAgent {
String TAG = “SystemWebAgent”;
protected WebViewInterface webViewInterface;
public SystemWebAgent(WebViewInterface webViewInterface) {
super();
this.webViewInterface = webViewInterface;
}

@Override
public void onLoadingPage(WebView webView, String url, PixelMap icon) {
    super.onLoadingPage(webView, url, icon);
    L.i(TAG,"onLoadingPage");
    // 页面开始加载时自定义处理
    if(webViewInterface!=null){
        webViewInterface.showWebViewLoading();
    }
}

@Override
public void onPageLoaded(WebView webView, String url) {
    super.onPageLoaded(webView, url);
    L.i(TAG,"onPageLoaded");
    // 页面加载结束后自定义处理
    if(webViewInterface!=null){
        webViewInterface.hideWebViewLoading();
        webViewInterface.onWebViewPageFinished();
    }
}

@Override
public void onError(WebView webView, ResourceRequest request, ResourceError error) {
    super.onError(webView, request, error);
    // 发生错误时自定义处理
    String url = request.getRequestUrl().toString();
    String err = error.toString();
    L.i(TAG,StringCompat.string("onError->url",url," err=",err));
}

@Override
public void onLoadingContent(WebView webView, String url) {
    super.onLoadingContent(webView, url);
    // 加载资源时自定义处理
}

@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
    if (request == null || request.getRequestUrl() == null) {
        L.i(TAG,"WebAgent isNeedLoadUrl:request is 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);
    }
}
@Override
public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
    final String authority = "example.com";
    final String rawFile = "/rawfile/";
    final String local = "/local/";
    Uri requestUri = request.getRequestUrl();
    String url = requestUri.toString();
    L.i(TAG, StringCompat.string("processResourceRequest->Uri=",url));
    if (authority.equals(requestUri.getDecodedAuthority())) {
        String path = requestUri.getDecodedPath();
        if (TextTool.isNullOrEmpty(path)) {
            return super.processResourceRequest(webView, request);
        }
        if (path.startsWith(rawFile)) {
            // 根据自定义规则访问资源文件
            String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
            String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
            L.i(TAG,StringCompat.string("processResourceRequest->rawFilePath=",rawFilePath));
            try {
                final Context context = webView.getContext();
                Resource resource = context.getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                return response;
            } catch (IOException e) {
                L.i(TAG, "open raw file failed");
            }
        }
        if (path.startsWith(local)) {
            // 根据自定义规则访问本地文件
            final Context context = webView.getContext();
            String localFile = context.getFilesDir() + path.replace(local, "/");
            L.i(TAG, "open local file " + localFile);
            File file = new File(localFile);
            if (!file.exists()) {
                L.i(TAG, "file not exists");
                return super.processResourceRequest(webView, request);
            }
            String mimeType = URLConnection.guessContentTypeFromName(localFile);
            try {
                InputStream inputStream = new FileInputStream(file);
                ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                return response;
            } catch (IOException e) {
                L.i(TAG, "open local file failed");
            }
        }
    }
    return super.processResourceRequest(webView, request);
}

}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
1
收藏
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐