我在Android中的Webview及其JavascriptInterfaces遇到问题。

我正在将字符串传递给JavascriptInterface。调试时,我在Android应用程序中收到正确的字符串。问题:有时会出现未捕获的错误:在NPObject上调用方法时出错。

有人知道为什么吗?

Java接口(interface):

public class JSInterfaceGame extends JSInterface {

@JavascriptInterface
public void setShareText(String share){
    shareText = share;
    if(mJSInterfaceListener != null)
        mJSInterfaceListener.onParametersChanged(SHARE_TEXT);
}

在Fragment中的onCreateView-Method中进行初始化:
online = (WebView) rootView.findViewById(R.id.online);
online.setWebViewClient(new WISWebviewClient() {
  @Override
  public void onStatusChanged(final WebView view, int progress, long duration) {
    //unrelated
  }
});

WebSettings ws = online.getSettings();
ws.setJavaScriptEnabled(true);
ws.setUserAgentString(USER_AGENT);
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
ws.setRenderPriority(WebSettings.RenderPriority.HIGH);

SharedPreferences settings = getActivity().getSharedPreferences(GameActivity.PREFERENCES, Context.MODE_PRIVATE);

mJSInterface = new JSInterfaceGame();
mJSInterface.setJSInterfaceListener(this); // Defined elsewhere in this class.
mJSInterface.setPlayerName(settings.getString(GameActivity.PREFS_PlAYERNAME, null));
online.addJavascriptInterface(mJSInterface, "JSInterface");
online.loadUrl("http://myurl.something");

用Java语言调用:
function makeShareText() {
  var text = "Some text";
  console.log(typeof text); // Always a string.
  JSInterface.setShareText(text);
}

最佳答案

当您尝试使用从javascript接口(interface)调用的方法与UI进行交互时,就会发生这种情况。要以这种方式解决它:

class mJSInterface()
{

public void myFunction()
{
    runOnUiThread(new Runnable() {

            public void run() {
                //Code that interact with UI
            }
        });

    }

}

10-08 05:43