JavaScript and Java interaction on Android WebView _android

Source: Internet
Author: User

In fact, the speed of webview loading resources is not slow, but if more resources, of course, is very slow. Pictures, CSS, JS, HTML, each of these resources probably need to 10-200ms, is generally 30ms on OK. However, WebView is required to wait until all resources have completed loading, will be rendered, so the speed of loading is very important! From Google we learned that the WebView load page order is: first load HTML, and then from the inside parsing CSS, JS file and the page picture resources to load. If the WebKit cache is inside, it is not loaded. After loading these resources, the CSS rendering and JS implementation. CSS rendering generally does not take a long time, dozens of milliseconds is OK. The key is the implementation of JS, if the use of jquery, it will take 5-6 seconds to execute. And in this time, if not in the WebView set the background, the page part is white, very difficult to see. This is a very bad user experience. So # Obi-K suggests that if you use a Web layout program, it's best not to use those huge JS frames. It is best to use the native JS write business script to improve the loading speed and the user experience.

In hybrid development, the Android native SDK is sometimes used, such as calling a camera, viewing a photo album, recording, and so on, which requires JavaScript on the Web page to invoke the Android SDK interface. Since the Android WebView is based on the WebKit kernel, the interface functions of JS and Java are integrated, which can be easily developed and used.

Interface Layout xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools= "http:// Schemas.android.com/tools "
android:layout_width=" match_parent "
android:layout_height=" Match_parent " >
<webview
android:id= "@+id/webview"
android:layout_width= "fill_parent"
android:layout_ height= "Fill_parent"
android:layout_above= "@+id/linearlayout"
/>
<linearlayout 
android : id= "@+id/linearlayout"
android:layout_width= "match_parent"
android:layout_height= "Wrap_content"
android:layout_alignparentbottom= "true"
>
<button
android:id= "@+id/btn"
Android:layout_width= "Wrap_content"
android:layout_height= "wrap_content"
android:text= " Java invoke JavaScript interface "
>
</Button>
</LinearLayout>

Java code:

Private WebView WebView;
Private Handler Handler = new Handler ();
Private button button; @SuppressLint ("setjavascriptenabled") @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (
Savedinstancestate);
Setcontentview (R.layout.activity_main);
WebView = (webview) Findviewbyid (R.id.webview);
Custom WebView settings WebSettings websettings = Webview.getsettings ();
Websettings.setjavascriptenabled (TRUE);
Webview.addjavascriptinterface (New Myjavascriptinterface (Mainactivity.this), "Javainterface");
If it is commented, the alert window in JavaScript is invalidated, and webview.setwebchromeclient (New Webchromeclient ()) is not displayed;
Webview.setwebchromeclient (New Mywebchromeclient ());
Test whether the webview load is normal//webview.loadurl ("http://www.baidu.com/");
Webview.setwebviewclient (New Hellowebview ());
Webview.loadurl ("file:///android_asset/index.html");
Button = (button) Findviewbyid (R.ID.BTN); Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {String param = "BB"; webvie W.loadurl ("JavascrIpt:showtitle (' "+param+") ");
}
}); Private class Hellowebview extends webviewclient{@Override public boolean shouldoverrideurlloading (WebView view, Strin 
G URL) {//TODO auto-generated method stub view.loadurl (URL); /** * Define JavaScript-callable Android interface * @author CHQ * API in the main thread, each called Java function is called Declaration @JavascriptInterface/public class MYJAVASCRI ptinterface{private context, public Myjavascriptinterface {this.context = context;} @Javascrip Tinterface public String toString () {return ' This is interface ';} @JavascriptInterface public void Clickonandroid () {To
Ast.maketext (context, "JS calls Android: ...", Toast.length_short). Show (); /** * Android Call JS interface, to open the child thread call/@JavascriptInterface public void called () {Toast.maketext (context, "Android client calls JavaScript interface", Toas
T.length_short). Show (); Handler.post (New Runnable () {@Override public void run () {String param = "BB"; Webview.loadurl ("Javascript:showtitle"
+param+ "')");
}
}); }
}

Among them: There are several points to note, the early online description of WebView, there are several changes. 1 Android more than 4.2 version of the use of WebView to achieve Java and JS Intermodulation, Java interface needs to declare @javascriptinterface; 2) WebView to call the Setwebchromeclient (), to adapt to the JS such as window and other implementations, 3) Addjavascriptinterface in the interface bound to invoke the JavaScript interface, You need to open a subroutine call (Error: caused By:java.lang.throwable:a WebView method is called on thread ' Javabridge '. All WebView methods must is called on the same thread. );

HTML code:

 
 

The above HTML file, where Javainterface is the interface entry name injected into the Addjavacriptinterface () method in WebView, where the interface in Java can be invoked directly. (The HTML page needs to be kept in the project assets directory, loaded by Webview.loadurl ("file:///android_asset/index.html");

Effect Chart:

In which, the dialog box pop-up: "file://" Web page shows: if the Web page on the server will show the source IP address, etc., obviously not what we want. Next, we can rewrite the webchromeclient to modify the WebView optimization of dialog boxes, confirmation boxes, and so on.

The above content is for Android WebView on the implementation of JavaScript and Java interaction of all content, I hope to help!

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.