Android App loading HTML5 page Solution Summary

Source: Internet
Author: User

Because the H5 page in the mobile side of the compatibility and extensibility of the advantages, but also for the app to be implanted H5 page corresponding flexibility has greatly improved (such as activities, game updates, etc.). App development inevitably needs to be loaded into some H5 pages. But the Android client may have some unpredictable problems with the layout, collation, and interaction of the content of the Web page. This article will be a summary of the Android loading Web page to write some common, possibly avoid problems of a unified solution.

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, image, etc.), sorting information (such as adding CSS, etc.), and calculate 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 WebView components for developers in front-end page loading. and give a response to the API to use. But the bottom of the kernel in 4.4 was once 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 through the Web page to open the local file selection The problem with the selector. In short, the technology is constantly maturing, interested in understanding the details of the http://blog.csdn.net/typename/article/details/40425275 incurable diseases recently made a project in which it was necessary to load an activity called the big turntable in the app. The active page is written with H5, so use WebView to load code such as the following:

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's the introduction. Why WebView both setwebclient, but also setwebchromeclient. The two are not because after 4.4 WebView adopted the chromium kernel 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, site icon, site title, loading progress, Detailed overridable interface you can check the SDK documentation yourself.

Back to the point, originally hoped the effect is the turntable can turn, all kinds of information including user information, picture information can display normal. Can really show that the effect is actually:

The turntable cannot be rotated. Users who are not shown. The number of draws is not shown, but the link is placed in the browser without any problem. Show Normal
Debugging in Chrome can infer that the front-end aspect of the code should be no problem, the problem should be in the WebView configuration, because I tested the phone is the Android 4.4 operating system. The H5 page and JS Interactive support is relatively intact, and in the mobile phone to enter the same link on the browser to perform normal, then the preliminary decision should be webview websettings problem. Also initially ruled out is the problem of JS, the English code has been set setjavascriptenabled (true). It says earlier that Android 4.4 and above WebView's kernel is chronium. One of the advantages that this brings to our app developers is the ability to debug with Chorme browser, debug location WebView load H5 page problems, open Chrome browser, plug in the phone, here is a brief description of the prerequisites (1, Phone if USB debug mode? 2, chromeclient need more than 31 ? 3, add the code

if (Build.VERSION.SDK_INT >= build.version_codes. KITKAT) {webview.setwebcontentsdebuggingenabled (true);}
)。It may also require FQ (this is very.)

. Just seems to FQ only once can be mobile phone installed program, connected to the computer, open the corresponding page (webviewactivity).

Click Inspect ( If this is not the case, you may need to FQ )

We click Console

> and then click inside to see what happened

consulted with the front-end colleagues, This is localstorage.getitem here because Localstorage is empty. Why is this, to here, need to add a localstorage knowledge. HTML5 storage mainly: sessionstorage: Session ( session) level of data storage, and the relevant data will be erased when the conversation is over.

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, which can be read by anyone, it is not advisable to store sensitive data here, despite the limitations. The Android default is to turn this feature off. 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 conquered, but assuming the problem, Chrome's devtools can not detect it? This is possible. As I said before, WebView parsing a webpage is most critical to the underlying parsing engine, and WebView simply invokes the engine's parsing function through JNI and encapsulates it for our Android developers. What about the phone terminal before 4.4? or webview the lightweight chronium kernel itself can not resolve the front-end developers of the awesome script do? While Google is constantly fixing bugs in version number iterations, it's undeniable that the version number of the Android phone you're using today is not aligned. The use of the high version of WebView words may encounter some wonderful problems, not to mention the lower version number. Of course, the future of our team WebView is very confident, the high version of the use of the increase. There will be fewer problems later, but now. Let's say you can try to crosswalk the WebView as a rich text editor in a comprehensive and stable way. 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, can first look at the effect.

about the beauty of the 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 usehigher level of use and understanding. Can participate in Crosswalk's official website. Https://crosswalk-project.org/documentation/embedding_crosswalk.htmldownload of crosswalk package: https://crosswalk-project.org/documentation/downloads.html1) Put the downloaded package in the same directory as the project where you need to use the package, and import the package project into eclipse. See the core engine from the Libxwalkcore.so library.


2) in the main project, join the library

3) Source code such as the following
<?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 nearly 20M. The APK app 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.


Cordova Let's say you're too crosswalk, and you don't want to webview on the code to ensure that you adapt to a variety of H5 pages. Perhaps Cordova is a good choice, in essence,Cordova is actually inherited WebView, so in the two are essentially the same , but I do not know how to debug webview before. The eldest brother did not want to use crosswalk this extremely occupies the space library. So I found Cordova jar package, in a word, the problem was conquered, 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 loading HTML5 page Solution Summary

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.