How to disable the main thread, how can I run any code for the main thread as quickly as possible?

I have a user interface partially based on the Web (WebView). It is connected to the Android UI through the Javascript Interface . When you click on an element in a WebView, javascript calls before Android and Android receive a call in javascript / web stream. Not a UI thread (main).

It arrives on Android in 1 or less milliseconds. No problems. However, since I want to change the user interface, I need to switch to the user interface thread. (Android throws an exception if you change the user interface from the main thread). I am currently using a handler in the user interface thread and calling post () .

This code (Runnable) is then called somewhere between 120 and 300 ms later. This is a very noticeable lag in changing the user interface from the user touch.

Is there a way to speed up some code in a user interface thread? Here is a sample code:

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 web view as follows:

 webview.addJavascriptInterface(new JSInterface(), "AndroidInterface"); 

Called in javascript as follows:

 AndroidInterface.test(); 

Thanks!

+7
source share
1 answer

Is there a way to speed up the execution of some code in a user interface thread?

runOnUiThread() and kin put the message in a message queue from which the main application thread is disconnected. In most cases, the main task of the application flow is to pull the message out of the queue and process it. However, the main application thread is responsible for calling most of your callbacks.

If you see delays of "120 and 300 ms", this means one of two non-mutually exclusive things:

  • There is a lag in the queue

  • The main application thread is busy executing different code.

The relationship between the WebView , the queue, and the main application thread is rather mysterious compared to regular widgets, because WebView not a classic widget displayed in Java code. Therefore, I have no idea if there is something happening in your web content that can explain this, or if this is normal for a WebView . You can try the experiment with simpler web content and see if you get similar delays, or if the delays are somehow more tied to the specific web content that you display.

Click to enter, use Handler and postAtFrontOfQueue() . Since JavaDocs are for this method , this is dangerous.

+6
source

All Articles