【问题标题】:JavaScript callbacks aren't being reached with android JSInterfaceandroid JSInterface 无法访问 JavaScript 回调
【发布时间】:2016-11-12 09:14:32
【问题描述】:

我想知道 responsivevoice (JS) 何时结束讲话。在文档here 中,它表明我可以传递像 onstart/onend 这样的回调。因此,我制作了一个 JSInterface 并将其附加到调用我的 JS 函数的 WebView 上。但是我不能正确地做,因为我的回调从未输入过。

这是我的 JSInterface:

private class JSInterface{
    @JavascriptInterface
    public void alertStart(){
        Log.i(TAG, "Speech started");
    }

    @JavascriptInterface
    public void stopService(){
        stopSelf(); //The whole point of this is to stop my Service.
    }
}

这里我把接口附在webview上:

final WebView webView = new WebView(context);
webView.setSoundEffectsEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(), "SpeechService");

这是我的 JS 函数:

function speak(text,voice,pitch,rate) {
    responsiveVoice.speak(text, voice,
        {
            onstart: alertStart,
            onend: stopService
        }
    );
}
function alertStart(){
    SpeechService.alertStart();
}

function stopService(){
    SpeechService.stopService();
}

我在这里的服务中使用我的 webView 调用该函数:

webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            if (sp.contains("voiceSettings")) {
                String voiceSettings = sp.getString("voiceSettings", "Voice settings not available");
                final String splitSettings[] = voiceSettings.split(":");
                Log.i("settings", Arrays.toString(splitSettings));
                webView.loadUrl("javascript:speak('" + text + "','" + splitSettings[0] + "','" + Double.parseDouble(splitSettings[1]) + "','" + Double.parseDouble(splitSettings[2]) + "')");
            }
            else{
                webView.loadUrl("javascript:speak('" + text + "','" + "UK English Male" + "','" + 1 + "','" + 1 + "')");
            }
        }
    });
    webView.loadUrl("file:///android_asset/tts.html");
}

提前致谢

【问题讨论】:

  • 你在哪里调用说话功能?你声明了语音字符串吗?
  • 我从我的代码中错误地复制了 js 语音标题,但我更新了它。我还添加了调用该函数的代码。您会看到我也在尝试为它传递声音、音高和音量。另外,现在它只进入那个 else 条件

标签: javascript android webview android-jsinterface


【解决方案1】:

原来,发送给 JS 函数的字符串中有一个撇号,导致语法不正确。所以该函数从未被调用。必须将输入包含在双引号中,以便包含所有撇号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多