Android 和 JS 交互时调用不成功的问题

 

具体如何交互,网上已经有很多资料,这里默认在已知如何交互的情况下,对几个重要的关键点进行强调。

1webView.getSettings().setJavaScriptEnabled(true);设置WebView支持JavaScript

2webView.addJavascriptInterface(new MyJavascriptInterface(), "android");绑定一个java对象到webview上,其实就是将一个java对象和网页JS关联起来,这样就可以使用JS调用该对象的方法等。

 

3、在MyJavascriptInterface对象中需要调用的方法上增加注解@android.webkit.JavascriptInterface;

 

4、若上面3个都已添加,还是无法调用。请检查清单文件(AndroidManifest.xml)android:targetSdkVersion="16" ,这里targetSdkVersion改成16

 

原因猜想:当你的targetSdkVersion17以上时,addJavascriptInterface会提示错误:“ None of the methods in the added interface have been annotated with @android.webkit.JavascriptInterface; they will not be visible in API 17 ”。大概意思就是说在注解@JavascriptInterface中的方法在API 17会不可见。以此来推断,你在电脑上用17以上的sdk编译你的java代码为.class字节码文件时,是会出问题的。

5、若必须使用高版本SDK编译,则添加注解 @SuppressLint("JavascriptInterface"),即可解决问题。

 

6、混淆注意,在混淆文件proguard-rules.pro里面,有这样一段话:

# If your project uses WebView with JS, uncomment the following

# and specify the fully qualified class name to the JavaScript interface

# class:

#-keepclassmembers class fqcn.of.javascript.interface.for.webview {

#   public *;

 

#}

把注释解除,把fqcn.of.javascript.interface.for.webview换成自己定义的MyJavascriptInterface全类名,再加上配置,

-keepattributes *Annotation*

-keepattributes *JavascriptInterface*

更多相关文章

  1. Android文件解压工具类
  2. android apk dex odex jar 等文件的 反编译工具
  3. 【转】android编译系统的makefile文件Android.mk写法
  4. Android+JNI调用–文件操作
  5. Android错误处理——Android读取txt文件乱码解决方案
  6. Android 10 创建文件失败
  7. IntentService通过HandlerThread单独开启一个线程来处理所有Inte

随机推荐

  1. Android(安卓)广播机制
  2. android IBeacon 开发(一)搜索IBeacon基站
  3. 利用HTML5开发Android笔记
  4. android 获得Android设备唯一标识码 ANDR
  5. android map (地图)
  6. android进程创建分析
  7. android adb
  8. Android中的事件分发机制
  9. Android(安卓)之 Window、WindowManager
  10. Android(安卓)1.5和Android(安卓)2.1在相