【GT-Android与JavaScript相互调用(二)】
前言:在上一篇文章中,已经分享了安卓端如何通过WebView调用JavaScript定义的方法来进行背景图片的设置,接下来在这篇文章中我将把如何在JS端调用Android端定义的方法分享给大家。
功能描述:JS端调用安卓端定义的截图函数,实现截图并保存至本地
首先,我们需要了解WebView的addJavaScriptInterface这个方法,看名字大致可以猜出他的意思增加一个JS接口,它有两个参数一个是对象,另一个则是对象名。其实简单来说就是利用这个方法将一个引用名与安卓定义的某个对象进行绑定,绑定成功后JS端便可以通过这个引用名调用对象定义的函数。
我们定义一个JsInterface类,代码如下:
我们可以看到,其中定义了一个带参的构造函数以及一个screenCut函数,定义好这个类之后,便可以调用WebView的addJavaScriptInterface方法传递该对象至JS端
当JS端获得这个对象后,便可以通过引用名调用JsInterface类中定义的screenCut函数,代码如下:
jsInterface.screenCut();
最后,将截图的工具类代码也分享给大家吧
public class CaptureTool { public static Bitmap captureWebView(WebView webView){ float scale = webView.getScale(); int width = webView.getWidth(); int height = (int) (webView.getHeight() * scale); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); webView.draw(canvas); return bitmap; } public static boolean saveBitmap(Bitmap bitmap,String path, String filename) throws IOException { File file = new File(path + filename); if(file.exists()){ file.delete(); } FileOutputStream out; try{ out = new FileOutputStream(file); if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) { out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); Log.e("eeeeee1",e.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); Log.e("eeeeee2",e.getMessage()); return false; } return true; } }