JS与Android WebView的简单交互 + WebView 的简单使用
16lz
2021-01-23
1.js调用android代码
放as文件夹下 image.png 小浩 //java 对应代码
@SuppressLint("SetJavaScriptEnabled") private void initWebView() { WebSettings settings = mWebView.getSettings(); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中 settings.setJavaScriptEnabled(true);//支持js settings.setBuiltInZoomControls(true); // 显示放大缩小 settings.setSupportZoom(true); // 可以缩放 settings.setUseWideViewPort(true);// 将图片调整到适合webview大小 settings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小 // settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//支持缓存 settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不支持缓存 settings.setAllowFileAccess(true); // 允许访问文件 //启用数据库 settings.setDatabaseEnabled(true); //设置定位的数据库路径 String dir = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setGeolocationDatabasePath(dir); //启用地理定位 settings.setGeolocationEnabled(true); //开启DomStorage缓存 settings.setDomStorageEnabled(true); // 设置允许JS弹窗 settings.setJavaScriptCanOpenWindowsAutomatically(true); // 启用javascript // 从assets目录下面的加载html mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } //处理javaScrip的Alter事件,这里也可以用android组件替换 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { return super.onJsAlert(view, url, message, result); } //加载进度条 @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } }); webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(this, "AndroidWebView");//对应js中的AndroidWebView.xxx //js调用本地文件跨域问题 try { Class<?> clazz = mWebView.getSettings().getClass(); Method method = clazz.getMethod( "setAllowUniversalAccessFromFileURLs", boolean.class); if (method != null) { method.invoke(mWebView.getSettings(), true); } } catch (IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } webView.loadUrl("file:///android_asset/index.html");}@JavascriptInterfacepublic void hello(String msg){//对应js中xxx.hello("") Log.e("webview","hello"); Toast.makeText(this,msg,Toast.LENGTH_LONG).show();}
需注意的是hello函数加上注解@javascriptInterface
2.android调用js代码:
js代码如下:
android代码如下:
public void click(View view){ webView.post(new Runnable() { @Override public void run() { webView.loadUrl("javascript:call()"); } });}
需要在子线程中调用
当android中的按钮被点击时会触发click方法,然后执行webview.loadUrl("javascript:call()"),然后js中正好有call这个方法,然后alert()就会被执行
3.简单使用
webview加载网页的核心方法是
public void loadUrl(String url) {}webView = (WebView) findViewById(R.id.webview);webView.loadUrl("http://www.baidu.com");
会发现你的app会自动打开手机系统自带的默认浏览器,这时候我们需要加:
webView.setWebViewClient(new WebViewClient()}
WebViewClient类中的几个方法在我们平时开发中大量的运用
public boolean shouldOverrideUrlLoading(WebView view, String url) { return false;}
一般情况下我们不需要重写,这个函数有一个返回值,当为false时意思是我们不用管,当前的webview自已加载这个url,当返回为ture时,就让我们自己操作。
public void onPageFinished(WebView view, String url) {}
当页面加载完成时调用,但需要注意的是
/** * When onPageFinished() is called, the * rendering picture may not be updated yet. To get the notification for the * new Picture, use {@link WebView.PictureListener#onNewPicture}. */
渲染图片有可能没有加载完成。
/** * Notify the host application that the WebView will load the resource * specified by the given url. * * @param view The WebView that is initiating the callback. * @param url The url of the resource the WebView will load. */public void onLoadResource(WebView view, String url) {}
这个函数是这要加载资源就会被调用。然后说一下错误处理的函数:
/** * Report an error to the host application. These errors are unrecoverable * (i.e. the main resource is unavailable). The errorCode parameter * corresponds to one of the ERROR_* constants. * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. * @deprecated Use {@link #onReceivedError(WebView, WebResourceRequest, WebResourceError) * onReceivedError(WebView, WebResourceRequest, WebResourceError)} instead. */@Deprecatedpublic void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {}
说一下webview缓存问题:有时候我们有缓存的需求,就是在没有网络的情况下,以前可以打开的网页也可以通过缓存文件打开,主要代码为:
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);webSettings.setAppCacheEnabled(true);String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gefdemoweb";Log.e(null,path);webSettings.setAppCachePath(path);第一行设置了缓存模式,第二行设置可以缓存,然后下面设置缓存路径,关于缓存模式有很多种:public static final int LOAD_DEFAULT = -1;//默认模式,当缓存资源是可用的不过期,就使用,否次网络加载public static final int LOAD_NORMAL = 0;//This value is obsolete,过时了,不用管public static final int LOAD_CACHE_ELSE_NETWORK = 1;//当缓存资源是可用的就使用,即使它是过期的,否次网络加载public static final int LOAD_NO_CACHE = 2;//不使用缓存public static final int LOAD_CACHE_ONLY = 3;//不使用网络然后说一下按返回键的问题,如果你不做任何设置,按返回键肯定要跳到上一个activity,但是我们想让他返回到上一个加载的网页怎么办:@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){ webView.goBack(); return true; } return super.onKeyDown(keyCode, event);}webSetting的其它常用设置:setJavaScriptEnabled(true); //支持jssetPluginsEnabled(true); //支持插件 setUseWideViewPort(false); //将图片调整到适合webview的大小 setSupportZoom(true); //支持缩放 setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局 supportMultipleWindows(); //多窗口 setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 setAllowFileAccess(true); //设置可以访问文件 setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点webview webSettings.setBuiltInZoomControls(true); //设置支持缩放 setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 setLoadWithOverviewMode(true); // 缩放至屏幕的大小setLoadsImagesAutomatically(true); //支持自动加载图片
更多相关文章
- Android matrix 控制图片的旋转、缩放、移动
- Android--SoLoader,android动态加载so库
- Android异步加载图像小结 (含线程池,缓存方法)
- Android TabHost使用、动态加载内容
- android WebView 图片缩放功能小结
- android使用inSampleSize、inScaled、inDensity、inTargetDensit
- android 怎么实现启动页提前加载webView里的内容
- android listview 自动加载
- Android 加载服务器上的图片