在我的 Android 应用程序中,我使用 WebAppInterface 从 Javascript 桥接到 Java。
我的 .html 文件包含一些运行“Android.canPlay();”的 JS在某些时候。
在我的应用程序中,函数“canPlay()”触发了一个可变监听器。
当变量监听器触发时,如果满足条件,一些文件将被重命名(临时文件,下载时带有 .tmp 附加扩展名,包括 .html 文件(所以它是 .html.tmp,原始 . html 与它并存))
重命名发生后,重新加载 Web View (我尝试同时使用函数和“.loadUrl()”——两者都会出错)
当需要在 webview 中重新加载 html 文件时,出现错误:
E/Web Console﹕ Uncaught Error: Error calling method on NPObject. at file:////mnt/sdcard/Download/qwerty/playlists/29/2/index.html:206
第 206 行是“Android.canPlay()”调用。
注意事项 - 如果我在重新加载 webview 之前没有重命名文件,而是从运行的后台服务中重命名,我就没有这个错误(尽管我确实得到了一个关于在 WebViewCoreThread 上运行东西的错误)
部分代码:
网络应用接口(interface)
public class WebAppInterface {
final Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void canPlay()
{
mPlaylistReady.changeState(true);
}
}
可变监听器(通过监听器类触发)(删除了一些代码,例如文件位置的共享首选项)
@Override
public void onStateChange(boolean state) {
if (state) { // true
// this finds all the files and removes the .tmp extension
fileRenamer.removeTmp(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/qwerty/playlists/"));
// reloads the webview
WebViewActivity.this.runOnUiThread(new Runnable() {
public void run() {
webView.loadUrl("file:///" + htmlFile.getAbsolutePath());
}
});
}
}
}
文件重命名器类
public class FileRenamer {
public void removeTmp(File directory)
{
File dir = directory;
if(dir.isDirectory()) {
for(File child : dir.listFiles()) {
String name = child.getName();
String ext = name.substring(name.lastIndexOf('.'));
if(ext.equals(".tmp")) {
final int lastPeriodPos = name.lastIndexOf('.');
File renamed = new File(dir, name.substring(0, lastPeriodPos));
child.renameTo(renamed);
}
}
}
}
}
最佳答案
此错误由 JavaScript 抛出,因为在 Java canPlay() 实现期间发生异常。
尝试将 WebAppInterface.canPlay() 方法封装在 try-catch 子句中并记录异常以找出可能发生的情况。
除此之外,我正在尝试发现一种在 JavaScript 上下文中映射异常的方法,但恐怕这是不可能的。
关于android - Javascript 接口(interface),错误 "Uncaught Error: Error calling method on NPObject",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20976487/