简体   繁体   English

Android中的速度更快:使用loadUrl将数据发送到WebView或使用JavascriptInterface从WebView检索数据?

[英]What's faster in Android: sending data to a WebView with loadUrl or retrieving it from the WebView with a JavascriptInterface?

I'm writing an Android app where I have to transfer many integers from my app's Java code to the Javascript in a WebView , so that they are displayed to the user. 我正在编写一个Android应用程序,我必须将许多整数从我的应用程序的Java代码传输到WebView中的Javascript ,以便它们显示给用户。

I see two ways of transferring this string: 我看到两种传输此字符串的方法:

  • Using loadUrl on the WebView: 在WebView上使用loadUrl

With an array data containing ints, I would use this code to transfer them to my webview. 对于包含整数的数组data ,我会使用此代码将它们传输到我的webview。

webView.loadUrl("javascript:loadData(" + data[0] + ");"); // data[0] is an int
webView.loadUrl("javascript:loadData(" + data[1] + ");"); // data[1] is an int
// etc.
  • Using JavascriptInterface : 使用JavascriptInterface

I have a Java class that holds the data array and exposes a method named getData(int x) , which just returns the value of data[x] . 我有一个Java类,它包含data数组并公开一个名为getData(int x)的方法, getData(int x)返回data[x]的值。 I can declare a JavascriptInterface so that method is visible to my Javascript code, which can then call it and get the data: 我可以声明一个JavascriptInterface,以便我的Javascript代码可以看到该方法,然后可以调用它并获取数据:

webView.addJavascriptInterface(backend, "dataBackend");

My question is this: which approach is faster? 我的问题是: 哪种方法更快? I imagine that if I have many elements in data , executing a lot of loadUrl() calls would be slow and buggy. 我想如果我在data有很多元素,执行大量的loadUrl()调用会很慢而且有问题。 But does the alternative work faster? 但替代方案的工作速度更快吗?

In general both loadUrl and jsInterface are not supposed to transfer large amounts of data. 通常,loadUrl和jsInterface都不应该传输大量数据。 But you can try building one large string from those integers and using it instead. 但您可以尝试从这些整数构建一个大字符串并使用它来代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM