【问题标题】:How to configure common data model across android and JS bridge?如何跨android和JS桥配置通用数据模型?
【发布时间】:2019-10-24 13:30:39
【问题描述】:

我在Android中有一个JS桥,

public class WebInterface {
    Context mContext;
    public WebInterface(Context c) { this.mContext = c;}

    @JavascriptInterface
    public void showAlert() {
         Toast.makeText(mContext, "This is being called from the interface", Toast.LENGTH_SHORT).show();
    }
}

我可以在我的webView中设置界面,

mWebView.addJavascriptInterface(WebInterface(this), "android"); 

这适用于像showAlert() 这样的简单方法,其中当参数或参数是简单字符串时没有参数,但是当我需要在从 Web 应用程序调用本机函数时将数据模型作为参数传递时,我该怎么做绑定数据模型?我需要调用实现具有自定义数据模型类型参数的函数。

public class WebInterface {
    Context mContext;
    public WebInterface(Context c) { this.mContext = c;}

    @JavascriptInterface
    public void showAlert() {
       Toast.makeText(mContext, "This is being called from the interface", Toast.LENGTH_SHORT).show();

    public void saveData(data: DataModel) { // DataModel is custom model
       Toast.makeText(mContext, "Saving data model", Toast.LENGTH_SHORT).show();
    }
}

如何跨原生应用和网络应用绑定数据模型。可以使用 TypeScript 吗?如果可以,如何配置?是否只能使用纯 json 字符串作为参数?没有别的办法吗?

【问题讨论】:

    标签: javascript android angularjs typescript web


    【解决方案1】:

    您应该使用 JSON 字符串。 您可以创建另一个函数接收您想要的格式,然后 JSON.stringify 传递给函数之前的对象。

    Javascript

    function saveData(obj){
      const json = JSON.stringify(obj);
      Android.saveData(json);
    }
    

    【讨论】:

    • json 字符串是一种可能的方式。还有其他方法吗?
    【解决方案2】:

    替代方法用于 JSON.parse(data)

    javascript

    function loadJson(obj) {
      var jsonValue = JSON.parse(obj)
      Android.saveData(jsonValue)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 2016-01-20
      • 2019-05-12
      • 2011-10-14
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多