如何强制Android WebView立即重新绘制/重新渲染



基本上JavascriptInterfaceWebView接收到Click事件,然后我需要多次更改HTML元素,问题是WebView只显示最后一次更改,这意味着渲染不是立即的。

问题:如何使webview.loadUrl("javascript:updateProgress(20);");生效并立即更改WebView内容?

----------------------------------

老问题:

我的WebView中有一个HTML进度条,我可以简单地通过从onCreate()运行webview.loadUrl("javascript:updateProgress(20);");来更新进度条值。

// JavaScript in WebView
function updateProgress(percentage){
document.getElementById('progressBar').style.width = percentage + '%';
}

现在,我有一个向连接的BLE设备发送二进制数据的类,我从Google BluetoothLeGatt中标记了这个例子,并在BluetoothLeService.java中添加了一个写入特性(发送数据(的方法。

public void WriteCharacteristic(BluetoothGattCharacteristic characteristic, byte[] data, MainActivity mainactivity){
byte[] data_twenty_byte = new byte [20];
int progress_count = 0;
while(get_next_twenty_byte(data, data_twenty_byte)){
characteristic.setValue(data_twenty_byte);
mBluetoothGatt.writeCharacteristic(characteristic);
progress_count++;
mainactivity.webview.loadUrl("javascript:updateProgress(" + progress_count + ");");
}
}

问题是当WriteCharacteristic()运行时,WebView不会更新(Redraw/Re-Re-ReRender(,WebView只有在WriteCharacteristic()完成后才会更新,平均进度条为100%。

注意:我已经尝试过runOnUiThread(new Runnable() {});

我的问题是,如何强制mainactivity.webview立即重新绘制?

谢谢你,

正如我的评论中所指出的,将长时间运行的进程推送到后台线程,然后在ui线程上运行webview更新应该可以实现您想要实现的目标。下面是我举的一个快速例子:

package com.example.myapplication
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebView
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
lateinit var webView: WebView
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = WebView(this)
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(this, "app")
setContentView(webView)
val html =
"""
<html>
<head>
<script type='text/javascript'>
function updateProgress(progress) {
let el = document.getElementById('progress');
el.innerText = progress;
}
</script>
</head>
<body>                    
<p>Value: <span id='progress'>0</span></p>
<button onclick='app.startUpdates();'>Start Update</button>
</body>
</html>            
""".trimIndent()
webView.loadData(html, "text/html", "UTF-8")
}
@JavascriptInterface
fun startUpdates() {
doSomething()
}
private fun doSomething() {
thread {
for (i in 1..100) {
runOnUiThread { webView.evaluateJavascript("updateProgress($i);", null) }
Thread.sleep(10)
}
}
}
}

最新更新