Javascript接口,错误“未捕获错误:错误调用NPObject上的方法”

时间:2014-01-07 16:13:43

标签: android android-webview android-file android-jsinterface

在我的Android应用程序中,我使用WebAppInterface从Javascript桥接到Java。

我的.html文件包含一些运行“Android.canPlay();”的JS在某些时候。

在我的应用程序中,函数“canPlay()”会触发变量侦听器。

当变量监听器触发时,如果满足条件,则重命名一些文件(临时文件,使用.tmp附加扩展名下载,包括.html文件(因此它是.html.tmp,与原始文件一起使用)。 html与它并存)))

重命名后,重新加载Web视图(我尝试使用一个函数,只是“.loadUrl()” - 两者都有错误)

当时间重新加载webview中的html文件时,我收到错误:

  

E / Web控制台:未捕获错误:在NPObject上调用方法时出错。在   文件:////mnt/sdcard/Download/qwerty/playlists/29/2/index.html:206

第206行是“Android.canPlay()”调用。

需要注意的事项 - 如果我在重新加载webview之前没有重命名文件,而是从运行的后台服务重命名,我没有这个错误(虽然我确实得到一个关于在WebViewCoreThread上运行的东西)

一些代码:

WebAppInterface

public class WebAppInterface {
    final Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void canPlay()
    {
        mPlaylistReady.changeState(true);
    }
}

变量监听器(通过监听器类触发)(删除了一些代码,例如文件位置的sharedprefences)

@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());
                }
            });

        }
    }
}

FileRenamer类

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);
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

JavaScript抛出此错误,因为在Java canPlay()实现期间发生了异常。

尝试将WebAppInterface.canPlay()方法封装在try-catch子句中,并记录异常以找出可能发生的情况。

除此之外,我正在尝试发现一种在JavaScript上下文中映射异常的方法,但我担心这是不可能的。

相关问题