Android and H5 Hybrid development

Source: Internet
Author: User

Android and H5 are widely used in mobile development applications. Many apps on the market are developed using Android, but using Android to develop some of the more complex sub-categories, suggestive pages are not worth the candle. And H5 in the production of cool animated web page compared to the force, and has the development speed, update does not rely on the app update, only need to update the corresponding page server, so the app and H5 page combination is particularly important. And Android and H5 can not exist independently, but affect each other. For example, the H5 page wants to get basic information about the user in the app, the app has to manipulate the H5 page, and so on.

Main function Points of this paper

1.webView How to load H5 page

2.Android How to call a method in H5

3.h5 How to call methods in Android

First, WebView How to load H5 page

1. Loading a remote page

(1) Adding permissions to the Androidmanifest.xml file

<uses-permission android:name= "Android.permission.INTERNET"/>

(2) Layout file Webview.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns: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"android:orientation= "vertical">    <WebViewAndroid:id= "@+id/wv_webview"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent" /></LinearLayout>

(3) Mainactivity.java

 Public classMainactivityextendsappcompatactivity {WebView WebView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.webview); WebView=(WebView) Findviewbyid (R.id.wv_webview);    Loadweb (); }     Public voidLoadweb () {//String url = "https://www.baidu.com/";String url = "file:///android_asset/index.html"; //This method can open a link in webview without jumping to an external browserWebview.setwebviewclient (Newwebviewclient ());    Webview.loadurl (URL); }    //overloads the onkeydown function so that it is rolled back within the page, rather than exiting the program directly     Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {        if(KeyCode = = Keyevent.keycode_back &&Webview.cangoback ())            {Webview.goback (); return true; }        return Super. OnKeyDown (KeyCode, event); }    }

2. Loading a local page

(1) New assets directory to store HTML pages

Right-click App->new->folder->assetsfolder

(2) HTML page into the assets directory

(3) Modify URL

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

Ii. How Android calls methods in H5

(1) Add WebView support for invoking the JS method

  //     support JavaScript parsing in HTML, whether it is not JS and Android interaction, as long as the page contains JS to
Webview.getsettings (). Setjavascriptenabled (True);
Support Popup window, that is, support HTML Web page frame
Webview.setwebchromeclient (New Webchromeclient () {
public boolean Onjsalert (WebView view,string url,string message,jsresult result) {
Return Super.onjsalert (View,url,message,result);
}
});
(2) Call H5 method without parameter return value (call directly)
H5 method:
Function Show () {
document.getElementById ("temp"). InnerHTML = "Hello World";
}
 Call:
Webview.loadurl ("Javascript:show ()");
(3) method of calling H5 with no return value
When calling a method with a H5 parameter, it is bound to pass in a string that is enclosed in single quotation marks when the fixed string is passed in, and an escape character is required when passing in the variable name.
H5 method:
function alertmsg (message) {
alert (message);
}
Call:
Webview.loadurl ("javascript:alertmsg (' haha ')");
String content = "9880";
Webview.loadurl ("Javascript:alertmsg (\" "+content+" \ ")");
(4) Call H5 with return value method
function sum (i,j) {
return i+j;
}
Call:
Webview.evaluatejavascript ("Sum", new Valuecallback () {
@Override
public void Onreceivevalue (Object value) {
Toast.maketext (mainactivity.this, "JS returns the result =" +value,toast.length_long). Show ();
}
});
   
Full code:
Index.html
<! DOCTYPE html>
Webview.xml
    
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout 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" android:orientation= "vertical" >    <button        android:id= "@+id/btn"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "button"        android:layout_ Marginbottom= "12DP"        android:layout_margintop= "8DP"/>    <webview        android:id= "@+id/wv_webview"        android:layout_width= "fill_parent"        android:layout_height= "fill_parent" >    </WebView>< /linearlayout>
Mainactivity.java
public class Mainactivity extends appcompatactivity {WebView WebView;    Button btn;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.webview);        BTN = (Button) Findviewbyid (R.ID.BTN);                Btn.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {//Call H5 no parameter no return value method                Webview.loadurl ("Javascript:show ()");                Call H5 with the method Webview.loadurl ("javascript:alertmsg (' haha ')");                String content = "9880";                Webview.loadurl ("Javascript:alertmsg (\" "+content+" \ ")");                    Call H5 has a return value method Webview.evaluatejavascript ("Sum", new Valuecallback () {@Override public void Onreceivevalue (Object value) {Toast.maketext (mainactivity.this, "JS returns the result =                    "+value,toast.length_long"). Show (); }                });            }        });        WebView = (WebView) Findviewbyid (R.id.wv_webview);    Loadweb (); } @SuppressLint ("Javascriptinterface") public void Loadweb () {String URL = "file:///android_asset/index.html        ";        This method can open a link in webView without jumping to an external browser webview.setwebviewclient (new Webviewclient ());        Webview.loadurl (URL); Support pop-up windows, that is, support for HTML Web page bullet box webview.setwebchromeclient (new Webchromeclient () {public Boolean onjsalert (WebView            view,string url,string Message,jsresult result) {return Super.onjsalert (View,url,message,result);        }        });    Support JavaScript parsing in HTML, whether it is not JS and Android interaction, as long as the page contains JS are webview.getsettings (). Setjavascriptenabled (True);        The public boolean onKeyDown (int keycode, keyevent event) {//Overrides OnKeyDown, and when the Web page is browsed, WebView can perform a back operation when it is back.            if (keycode = = Keyevent.keycode_back && webview.cangoback ()) {webview.goback ();        return true; } return SupeR.onkeydown (keycode,event); }}
Third, H5 how to call the method in Android
Android needs to create a new class that provides methods for H5 operations and specifies aliases.
(1) Create a new class
    
Public  class  jsinteration  {
@JavascriptInterface
Public String Back () {
Return "Hello World";
}
}
(2) WebView Add JS interface, and Alias
  
Webview.addjavascriptinterface (New Jsinteration (), "Android");
(3) H5 call
    
Window.android.back ();
Full code:
Index.html
<!DOCTYPE HTML><HTML><Head><title>Test</title></Head><BodyOnLoad= "init ();">    <DivID= "Temp">H5 page</Div>    <ButtonID= "BTN"onclick= "getmsg ()">Button</Button></Body><Scripttype= "Text/javascript">    functiongetmsg () {varresult=Window.android.back (); document.getElementById ("Temp"). InnerHTML=result; }</Script></HTML>

Mainactivity.java
public class Mainactivity extends appcompatactivity {WebView WebView;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);            Setcontentview (R.layout.webview);        WebView = (WebView) Findviewbyid (R.id.wv_webview);    Loadweb (); } @SuppressLint ("Javascriptinterface") public void Loadweb () {String URL = "File:///android_asset/dj_index.h        Tml ";        This method can open a link in webView without jumping to an external browser webview.setwebviewclient (new Webviewclient ());        Webview.loadurl (URL);    /* Open JS Interface, parameter 1 is the local class name, Parameter 2 is alias */Webview.addjavascriptinterface (new Jsinteration (), "Android");            } public class Jsinteration {@JavascriptInterface//must be written, otherwise h5 cannot be transferred to this method public String back () {        Return "Hello World";        }} public boolean onKeyDown (int keycode, keyevent event) {//Overrides OnKeyDown, when browsing the Web page, WebView can perform a back operation when it is back. if (keycode = = Keyevent.keycode_back && Webview.cangoback ()) {webview.goback ();        return true;    } return Super.onkeydown (keycode,event); }}

Android and H5 Hybrid development

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.