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.