Android Hybrid Development, WebView Java and JS interoperability

Source: Internet
Author: User

Android native app, use WebView to load Web pages in your app, and Java code and JS code can interoperate with each other.

This is the cornerstone of hybrid development, the most basic and most important thing, the experimental code here.

To sum up, say--

java Tune JS: call Webview.load ("Javascript:somefunction ()");

This allows you to invoke the global method on the page in WebView. This is not a new thing, you can also do this in the Web page, try to enter Javascript:alert ("427studio") in the browser address bar, or you can call the global method in the browser address bar.

js tune Java: call Webview.addjavascriptinterface (Somepojo, "varName");

Having a Java object become the VarName property of a Window object inside a WebView page is like performing a window.varname = Somepojo, because window is the global context, JS can access this Java object in a way that accesses a global variable, and then call the object's function, and if Somepojo has a public void doIt () method, it can be called: somebutton.onclick= function () {Varname.doit ();}

Specific code: look here and here, are very basic, briefly listed as follows:

1.activity, Tune JS method there hand itch smoked a method, the diagram simple direct spell "javascript:jsdoit ('" + xx + "');" And nothing.

By the Loadurl, load the Android program assets the resources in the package to file:///android_asset/ start, such as file:///android_asset/ Index.html means to load the index.html file in the assets package.

Package Com.example.testhybrid;

Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.webkit.JavascriptInterface;
Import Android.webkit.WebView;

public class Mainactivity extends Activity {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

if (savedinstancestate = = null) {
Getfragmentmanager (). BeginTransaction ()
. Add (R.id.container, New Placeholderfragment ())
. commit ();
}
}
}

Class Placeholderfragment extends Fragment {

WebView WebView;

Public Placeholderfragment () {
}

@SuppressLint ("setjavascriptenabled") @Override
Public View Oncreateview (layoutinflater inflater, ViewGroup container,
Bundle savedinstancestate) {
View Rootview = inflater.inflate (R.layout.fragment_main, container, false);

WebView = (WebView) Rootview.findviewbyid (R.ID.WEBVIEW1);

Webview.getsettings (). Setjavascriptenabled (True);

Handler Handler = new Handler () {
@Override
public void Handlemessage (Message msg) {
String str = Msg.getdata (). getString ("str");
Dojs ("Jsdoit", Str.replaceall ("\\d", ""));
}
};
Webview.addjavascriptinterface (New Myjavascriptinterface (WebView, Handler), "Javaobject");

Webview.loadurl ("file:///android_asset/webviews/index.html");

return rootview;
}

//Call JS method, the first parameter is the JS method name, and the following parameter is the parameter list of the JS method
void Dojs (String function, Object ... params) {
StringBuilder result = new StringBuilder ();
Result.append ("javascript:"). Append (function). Append ("(");
for (int i = 0; i < params.length; i++) {
Result.append ("'"). Append (Params[i].tostring ()). Append ("'");
if (I < params.length-1) {
Result.append (",");
}
}
Result.append (")");
String jsstr = result.tostring ();
Webview.loadurl (JSSTR);
}
}

The Java object to be used for JS invocation
Class myjavascriptinterface{

Myjavascriptinterface (WebView WV, Handler h) {
This.thewebview = WV;
This.handler = h;
}

WebView Thewebview;
Handler Handler;

//Java method to be used for JS invocation
@JavascriptInterface
public void Javadoit (final String str) {
Message msg = new Message ();
Bundle bundle = new bundle ();
Bundle.putstring ("str", str);
Msg.setdata (bundle);
Handler.sendmessage (msg);
}

}

Web page structure is not redundant, JavaScript code:

HTML button click Trigger
function thebtnonclicked () {
//Call Java method
Javaobject.javadoit ("427studio");
}

The JS method to be used by the Java program to invoke
function Jsdoit (str) {
document.getElementById (' thebtn '). InnerText + = str;
}

Long-term welcome project Cooperation Opportunity Introduction, project income 10% to reward introducer. Sina Weibo: @ Cold Mirror, qq:908789432.

Android Hybrid Development, WebView Java and JS interoperability

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.