Android App Load HTML5 page Solution Summary

Source: Internet
Author: User
Tags chrome devtools

Because the H5 page in the mobile side of the compatibility and extensibility of the advantages, but also for the application of the H5 page embedded in the app's flexibility has greatly improved (such as activities, game updates, etc.), app development inevitably need to load some H5 page, but the Android client page content of the typesetting, collation, Interactions, and so on, may cause unexpected problems. This article will be on the Android load Web page to write some more general, may avoid the problem of a unified solution summary.

Backgroundgeneral knowledge of the front end is clear, the analysis of the page is mainly by the page rendering engine and the JS parsing engine, the former is responsible for obtaining the content of the Web page (HTML, XML, images, etc.), sorting information (such as CSS, etc.), and the calculation of the display of the Web page will then output to the display or printer, The latter is responsible for some of the dynamic interaction of web pages. The Android operating system provides the developer with WebView components for front-end page loading, and gives the response API to use, But the bottom of the kernel before 4.4 is the WebKit kernel (H5 support is not enough), 4.4 is the chromium kernel (JS parsing engine is now the most commonly used V8 engine, the support of H5 gradually increased), with the continuous iteration of the Android operating system, 5.0 has been resolved to open the local file selector via the Web page The problem, in short, technology in the continuous maturity, interested in understanding the details of the reference http://blog.csdn.net/typename/article/details/40425275Difficult diseasesrecently did a project, inside need to load in the app is called the big turntable activity, the activity page of course is written with H5, so the loading code with WebView is as follows:
Package Com.example.webviewtest;import Android.annotation.suppresslint;import Android.app.activity;import Android.content.context;import Android.graphics.bitmap;import Android.net.http.sslerror;import Android.os.Build; Import Android.os.bundle;import Android.support.v4.app.fragmentactivity;import Android.view.keyevent;import Android.webkit.jsresult;import Android.webkit.sslerrorhandler;import Android.webkit.webchromeclient;import Android.webkit.websettings;import android.webkit.webview;import android.webkit.WebViewClient; @SuppressLint (" Setjavascriptenabled ") public class Webviewactivity extends Fragmentactivity {private WebView webview;private Context Context;private activity activity; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_webview); context = This;activity = This;initview ();} private void Initview () {WebView = (WebView) Findviewbyid (R.ID.GAME_WV); Initwebview ();} @SuppressLint ("Newapi") private void INITWEbview () {if (Build.VERSION.SDK_INT >=) {webview.getsettings (). Setcachemode (Websettings.load_cache_else_ NETWORK);} Webview.setwebchromeclient (New Webchromeclient () {@Overridepublic void onprogresschanged (webView view, int newprogress) {super.onprogresschanged (view, newprogress); Activity.settitle ("Loading ..."); Activity.setprogress ( Newprogress *), if (newprogress = =) {Activity.settitle (r.string.app_name);}} @Overridepublic Boolean Onjsalert (WebView view, string URL, string Message,jsresult result) {return Super.onjsalert (view , URL, message, result);}); Webview.setwebviewclient (New Gamewebviewclient ()); websettings s = webview.getsettings (); s.setjavascriptenabled (true); Webview.loadurl (Constants.url);} Class Gamewebviewclient extends Webviewclient {@Overridepublic boolean shouldoverrideurlloading (WebView view,string url_turntable) {View.loadurl (url_turntable); return true;} @Overridepublic void Onreceivedsslerror (WebView view, Sslerrorhandler handler,sslerror error) {Handler.proceed();} @Overridepublic void onpagestarted (WebView view, String URL, Bitmap favicon) {} @Overridepublic void onpagefinished ( WebView view, String URL) {}} @Overridepublic boolean onKeyDown (int keycode, keyevent event) {if (keycode = = KEYEVENT.KEYC Ode_back) && Webview.cangoback ()) {webview.goback (); return true;} Return Super.onkeydown (KeyCode, event);}}
Here is a brief introduction, why WebView both setwebclient, but also setwebchromeclient, The two are not because after 4.4 webview adopted the kernel of chromium so later abandoned the WebClient (before a lot of children's shoes misunderstood), in fact, the two are complementary:
webviewclient mainly help WebView handle various notifications, request events, webchromeclient main auxiliary webview Processing JavaScript dialog box, website icon, site title, loading progress, Specific overridable interfaces You can check the SDK documentation yourself. Back to the point , originally hoped that the effect is the turntable can turn, all kinds of information, including user information, picture information can be displayed normal, can really show that this effect:

turntable can not be rotated, the user is not displayed, can draw the number of times also not shown, but the link into the browser but no problem, display normal
Debug with Chrome browsercan judge the front-end aspect of the code should be no problem, the problem should be on the WebView configuration, Because I test the mobile phone is the Android 4.4 operating system, the H5 page and JS Interactive support is relatively perfect, and in the mobile phone comes with the same link on the browser to run normal, then the preliminary decision should be webview websettings problem, but also the initial exclusion is the problem of JS, the English code has Setjavascriptenabled (True) is set. Said earlier Android 4.4 above WebView kernel is chronium, this gives our app developer another benefit is that can use Chorme browser debugging, debug location WebView load H5 page encountered problems,, open the Chrome browser, Plug in the phone, in this brief description of the prerequisites (1, mobile phone if USB debugging Mode 2, chrome client needs more than 31 3, the code added
if (Build.VERSION.SDK_INT >= build.version_codes. KITKAT) {webview.setwebcontentsdebuggingenabled (true);}
). you may also need to flip the wall (this is ...). , but it looks like you just have to flip the wall once. mobile phone installed program, connected to the computer, open the corresponding page (webviewactivity).

Click Inspect ( if not, you may need to flip the wall )The following interface appears

We click Console

then go in and see what's going on.

Consulting the next to do the front-end colleague, here is localstorage.getitem because Localstorage is empty, why this, to here, need to add localstorage knowledge. HTML5 storage mainly include:Sessionstorage: Session-level data storage, and when the session is finished, the associated data is erased. localstorage: For persistent local storage, the data will never expire unless the data is actively deleted. as part of the HTML5 standard, most browsers support Localstorage, but given its security features (anyone can read it, and despite the limitations, storing sensitive data here is still not advisable), Android turns off the feature by default. in other words, the parsing of H5 pages that write such code also needs to be added in the code above:
S.setdomstorageenabled (TRUE);
tested successfully! CrosswalkThe above problem is solved, but if there is a problem, chrome devtools can not detect it? This is possible, said before, WebView parsing the page is the most critical to rely on the underlying parsing engine, WebView only through JNI call the engine parsing function and encapsulated for our Android developers to use. What about the phone terminal before 4.4? or webview the lightweight chronium kernel itself can not resolve the front-end developer's awesome script to do? Although Google is constantly fixing bugs in version iterations, it is undeniable that the current version of the Android phone you use is uneven, the high version of the use of WebView words may encounter some wonderful problems, not to mention the lower version of the. Of course, our team WebView the future is very confident, high version of the use of the increase in the future, these problems will be less, but now, if you webview as a rich text editor in comprehensiveness and stability is not very satisfied, you can try crosswalk. Crosswalk IntroductionCrooswalk, not only is he efficient, stable, and load the same interface, the font will look good, it is said that the 3D effect is also very ideal, you can first look at the effect.

about its cool place, do not repeat here, interested in children's shoes can look at this article http://dev.yesky.com/24/39285024.shtml, tells about his development history and advantages. Crosswalk Android End usemore advanced use and understanding, can refer to Crosswalk's official website, https://crosswalk-project.org/documentation/embedding_crosswalk.htmldownload of crosswalk package: https://crosswalk-project.org/documentation/downloads.html1) will download the package, and the project you need to use the package in the same folder, import the package in Eclipse Project, see its core engine from the Libxwalkcore.so library.


2) in the main project, add the library

3) The source code is as follows
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <org.xwalk.core.xwalkview        android:id= "@+id/game_wv"        android:layout_ Width= "Match_parent"        android:layout_height= "Match_parent"/></linearlayout>

Package Com.example.webviewtest;import Org.xwalk.core.xwalkresourceclient;import Org.xwalk.core.xwalkview;import Android.annotation.suppresslint;import Android.content.context;import Android.os.bundle;import Android.support.v4.app.FragmentActivity, @SuppressLint ("setjavascriptenabled") public class Crosswalkactivity Extends Fragmentactivity {Private Xwalkview webview;private context context; @Overridepublic void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_crosswalk); context = This;initview ();} private void Initview () {WebView = (Xwalkview) Findviewbyid (R.ID.GAME_WV); Initwebview ();} private void Initwebview () {webview.setresourceclient (new gamewebviewclient (WebView)); Webview.load (Constants.url, NULL);} Class Gamewebviewclient extends Xwalkresourceclient{public gamewebviewclient (Xwalkview view) {Super view;} @Overridepublic void onloadstarted (xwalkview view, String URL) {super.onloadstarted (view, URL);} @Overridepublic void OnloadfiniShed (xwalkview view, String URL) {super.onloadfinished (view, URL);}}} 
Crosswalk DisadvantagesIf there is any disadvantage of crosswalk, it is too big, a. So dynamic library is full of nearly 20m,apk application itself may not be enough for his 1/4. Single This also see the amount of its code is huge, the effect of a comprehensive that is beyond doubt.
CordovaIf you too crosswalk too big, and do not want to webview in the code to make various settings to ensure that adapt to a variety of H5 pages, perhaps Cordova is a good choice, in essence,Cordova actually inherited WebView, So in the two they are essentially the same , but in between I did not know how to debug WebView, the eldest brother did not want to use crosswalk this extremely occupy the space of the library, so I found the Cordova jar package, in short, the problem solved it, but now look back, Cordova after 4.0 has chosen to cooperate with crosswalk, I use the jar package is still 3.7, it is recommended that no longer use it. But now that you've done that, put the diagram and code on it.



<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <org.apache.cordova.cordovawebview        android:id= "@+id/game_wv"        android: Layout_width= "Match_parent"        android:layout_height= "Match_parent"/></linearlayout>

Package Com.example.webviewtest;import Java.util.arraylist;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Org.apache.cordova.cordovachromeclient;import Org.apache.cordova.cordovainterface;import Org.apache.cordova.cordovaplugin;import Org.apache.cordova.cordovapreferences;import Org.apache.cordova.cordovawebview;import Org.apache.cordova.cordovawebviewclient;import Org.apache.cordova.pluginentry;import Org.apache.cordova.whitelist;import Android.annotation.suppresslint;import Android.app.activity;import Android.content.context;import Android.content.intent;import Android.os.bundle;import Android.support.v4.app.fragmentactivity;import android.view.KeyEvent; @SuppressLint ("setjavascriptenabled") public class Cordovaactivity extends Fragmentactivity implements Cordovainterface {private final Executorservice ThreadPool = Executors.newcachedthreadpool ();p rivate cordovawebview webview;private int activityrequestcode;private Cordovaplugin ActivityresultCallback;private cordovapreferences prefs = new Cordovapreferences ();p rivate Whitelist internalwhitelist = new Whitelist ();p rivate Whitelist externalwhitelist = new Whitelist ();p rivate arraylist<pluginentry> pluginentries;private context context; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_cordova); context = This;initview ();} private void Initview () {WebView = (Cordovawebview) Findviewbyid (R.ID.GAME_WV); Initwebview ();} private void Initwebview () {internalwhitelist.addwhitelistentry ("*", false); Externalwhitelist.addwhitelistentry (" Tel:* ", false); Externalwhitelist.addwhitelistentry (" sms:* ", False);p Refs.set (" LogLevel "," DEBUG "); Webview.init ( This, makewebviewclient (WebView), Makechromeclient (WebView), Pluginentries, Internalwhitelist, Externalwhitelist, Prefs); Webview.loadurlintoview (Constants.url);} Private Cordovawebviewclient makewebviewclient (Cordovawebview webView) {return webview.makewebviewclient (this);} Private Cordovachromeclient makechromeclient (Cordovawebview webView) {return webview.makewebchromeclient (this);} @Overridepublic Activity getactivity () {//TODO auto-generated method Stubreturn this;} @Overridepublic Executorservice Getthreadpool () {//TODO auto-generated method Stubreturn ThreadPool;} @Overridepublic Object OnMessage (String arg0, object arg1) {if (Arg0.equals ("onpagestarted")) {}if (Arg0.equals (" Onpagefinished ")) {}return null;} @Overridepublic void Setactivityresultcallback (Cordovaplugin arg0) {if (activityresultcallback! = null) { Activityresultcallback.onactivityresult (Activityrequestcode, activity.result_canceled, null);} This.activityresultcallback = arg0;} @Overridepublic void Startactivityforresult (Cordovaplugin arg0, Intent arg1, int arg2) {Setactivityresultcallback (arg0 ); Startactivityforresult (Arg1, Activityrequestcode);} @Overridepublic boolean onKeyDown (int keycode, keyevent event) {if (keycode = = keyevent.keycode_back) {}return Super.onkeydown (KeyCode, event);}}
Summarysaid so much, I still suggest that you use the Android SDK to provide the components and features, after all, the function can be packaged themselves, out of the problem debugging is also convenient, WebView is constantly updating the iteration, we still have to be confident about it.
accessories:http://download.csdn.net/detail/zcchange1025/9455185

Android App Load HTML5 page Solution Summary

Related Article

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.