《安卓原生加载本地webview方法 | 社区征文》

安卓工程打开此路径

找到这个类

image

添加重写的方法

 @Override
         public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
             //chenym-debug
             String assetPath = url;
             if(assetPath!=null&&assetPath.contains("https://localhost/zip//")){
                 try {
                     String pathname = assetPath.replace("https://localhost/zip//","");
                     if(pathname.contains("html?")){
                         pathname=pathname.split("\\?")[0];
                     }
//                     File file = new File( pathname);
//                     InputStream is= new FileInputStream(file);
                     InputStream is=getContext().getAssets().open(pathname);
                     String mimeType = "text/html";
                     String extension = MimeTypeMap.getFileExtensionFromUrl(pathname);
                     if (extension != null) {
                         if (pathname.endsWith(".js") || pathname.endsWith(".mjs")) {
                             // Make sure JS files get the proper mimetype to support ES modules
                             mimeType = "application/javascript";
                         } else if (pathname.endsWith(".wasm")) {
                             mimeType = "application/wasm";
                         } else {
                             mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                         }
                     }

                     return new WebResourceResponse(mimeType, null, is);
                 } catch (Exception e) {
                     e.printStackTrace();
                     Log.e(TAG, e.getMessage());
                 }
                 return null;
             }
             return   super.shouldInterceptRequest( view,  url) ;

         }

使用方式

传入给webview.url=“https://localhost/zip//”+本地路径

举例

image

加载上图本地index.html,传给webview.url=“https://localhost/zip//assets/webViewDemo/index.html

1赞