如何传递返回值从javascript函数到Android? [英] How do I pass return values from a javascript function to android?

查看:568
本文介绍了如何传递返回值从javascript函数到Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的机器人应用调用写在的javascript 的函数,并从期望返回值。

I want to let my android app call a function written in javascript and expect a return value from that.

据我所知, WebView.loadUrl 以异步方式工作,所以我在做什么,现在是让JavaScript的通知我的Andr​​oid应用程序,当它完成,并通过调用使用Java函数传递的返回值< STRONG> javascriptinterface

I understand that WebView.loadUrl works asynchronously, so what I am doing now is to let javascript notify my android app when it is done and pass in the return value by calling a java function using javascriptinterface.

我不知道是否有这样做的,以及是否有人已经注意到了JavaScript和机器人之间的任何消息丢失的更好的方法。

I wonder if there are better ways of doing this and whether anyone has noticed any message loss between javascript and android.

推荐答案

我刚收到你的问题。

有一个JS的功能是这样的。

Have a JS function like this.

function androidResponse() {
   window.cpjs.sendToAndroid("I am being sent to Android.");
}

设置的Andr​​oid(Java)。

Set up Android (Java).

有这样的final类

final class IJavascriptHandler {
   IJavascriptHandler() {
   }

   // This annotation is required in Jelly Bean and later:
   @JavascriptInterface
   public void sendToAndroid(String text) {
      // this is called from JS with passed value
      Toast t = Toast.makeText(getApplicationContext(), text, 2000);
      t.show();
   }
}

然后在你的WebView负载有。

Then on your WebView load have.

webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");

JS调用功能

Call JS function

webView.loadUrl("javascript:androidResponse();void(0)");

更新时间:

另外,我有一个非常糟糕的时候遇到的问题,同时通过数百串线,以JS从Java和我以后的岗位上StackOverflow的,没有很好的答案,但最终解决它知道problme是在字符串的特殊字符,以便采取特殊字符当您使用字符串中传递来来回回。

Also I had a very bad time experiencing problems while passing hundreds of lines of string to JS from Java and I have subsequent post on StackOverflow with no good answers but finally resolved it knowing problme was of special characters inside string so take of special characters when you use string passing to and fro.

<一个href="http://stackoverflow.com/questions/4906158/passing-data-from-javascript-to-android-webview">Passing数据从Javascript到Android的WebView

HTML字符串内嵌套的字符串

<一个href="http://stackoverflow.com/questions/5002417/html-textarea-characters-limit-inside-android-webview">HTML文本区字符的限制内机器人的WebView

这篇关于如何传递返回值从javascript函数到Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆