I have an user interface that is partly web based (WebView). It is connected to the Android UI through a Javascript Interface. When you tap on an element in the WebView, javascript calls up to Android and Android receives the call on the javascript/web thread. Not the UI (main) thread.
It arrives in Android in 1 or less milliseconds. No problem there. However, because I want to now change the UI, I have to switch over to the UI thread. (Android throws an exception if you modify the UI from off the main thread). I am currently using a Handler on the UI Thread and calling post().
This code (a Runnable) is then called anywhere between 120 and 300 ms later. This is a very noticeable lag for the UI to change from the user's touch.
Is there any way to get some code to run on the UI thread faster? Here is some example code:
An interface class:
public class JSInterface {
public void test() {
// Arrives here in 1ms after calling AndroidInterface.test(). Arrives n the web thread.
runOnUiThread(new Runnable() {
@Override
public void run() {
// Arrives here 100ms to 300ms after calling AndroidInterface.test(). Arrives on the main (UI) thread.
}
});
}
}
Added to a webview like this:
webview.addJavascriptInterface(new JSInterface(), "AndroidInterface");
Called in javascript like this:
AndroidInterface.test();
Thanks!
Is there any way to get some code to run on the UI thread faster?
runOnUiThread()
and kin put a message on a message queue that the main application thread works off of. Much of the time, the main application thread's job is to pull a message off the queue and process it. However, the main application thread is responsible for calling most of your callbacks as well.
If you are seeing "120 and 300 ms" delays, that means one of two not-mutually-exclusive things:
The queue has quite the backlog
The main application thread is busy executing some other code
The relationship between WebView
, the queue, and the main application thread is rather mysterious, compared to normal widgets, because WebView
isn't a classic widget rendered in Java code. Hence, I have no idea if there is something that is occurring in your Web content that might explain this, or if this is fairly normal for WebView
. You might try an experiment with simpler Web content and see whether you get similar delays, or if the delays are somehow more tied to the specific Web content that you are rendering.
Push come to shove, use Handler
and postAtFrontOfQueue()
. As the JavaDocs for that method note, though, this is dangerous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With