[Android] WebView method must on same thread

Source: Internet
Author: User

The problem description recently used WebView in the code, mainly using WebView to load the remote URL. But when I implemented the JavaScript interface and called the JavaScript method to refresh the URL, I found that the refresh code didn't actually work. The sample code is as follows:
public void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.main_layout);        Final WebView WebView = (WebView) Findviewbyid (R.id.webview);        Webview.getsettings (). Setjavascriptenabled (true);        Webview.setwebchromeclient (New Webchromeclient ());        WebSettings websettings = Webview.getsettings ();        Websettings.setjavascriptenabled (true);        JAVASCR = new Androidjavascript (this, webView);        Webview.addjavascriptinterface (JAVASCR, "androidfunction");        Webview.loadurl ("file:///android_asset/www/index.html");}
Androidjavascript.java
public class Androidjavascript {       Context cont;    WebView WebView;    Androidjavascript (Context C, WebView W) {        cont = c;        WebView = w;    }    Function called in the JavaScript by Androidfunction.test ();    public void Test () {        Webview.loadurl ("Javascript:helloback ()");}    }

The problem-solving JavaScript interface method is executed in a background thread, not in the main thread. However, all methods related to the Android UI need to be called in the main UI thread. Therefore, the Post method is required to transfer the load URL operation to the main thread, as shown in the following example code:
    public void Test () {        webview.post (new Runnable () {public            void run () {                Webview.loadurl ("javascript: Helloback () ");            }        );}    
This can be done by placing the task in the main UI thread.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.