Integrate original Android applications with jquery Mobile: Case Study

Source: Internet
Author: User
Tags call back
Preface:

For a long time, I have been thinking about when to develop an app Based on Web apps developed by native HTML5. Finally, I made an application called Libo parenting encyclopedia, I tried this method to create an app;

Author of this article: The Heart of the ghost heart, blog address: http://blog.csdn.net/changemyself, microblogging address: http://weibo.com/changeself

If you want to reprint this article, add the address and name of this article, and do not delete the original link;

Project Introduction:

This is an encyclopedia app that mainly contains information on parenting, health care, pregnancy, diet, Maternal and Child supplies, and other aspects. These materials are all in HTML format, use CSS to store segments in the database;

Considering the need for an android and IOS version, we should try to share the webpage content on two systems, maintain a webpage content, and use it on two mobile platforms;

In terms of APP operation and usage, the main interface is the encyclopedia category. Then, the user enters the category to display the label items under the category. The user can use the label items to further find the encyclopedia articles he/she wants to see; of course, there are also "Article favorites" and "Article Search" features.

:

On the article page, the UI style of jquery mobile is used: the page title bar + content bar. When you click the page, the page title bar will be automatically hidden/displayed. If the page is displayed more than one screen, I added a shortcut "Back to Top" in the bottom right corner of the page. Of course, there are two buttons in the title bar of the page: "back" and "add to Favorites, they help users return to the previous page and add favorite articles.

:

Introduction to interfaces between native and HTML5:

This is the focus of this article,

Preparations: First, I used the python and Django template Technology Prize database to generate static html pages in batches Based on the template made by jquery UI, which is about 20 mb, I directly threw them to the/asset directory for webview loading and usage.

Code Design: The webview that loads HTML5 web pages is embedded in an activity, which is called webpageactivity;

We also need to add a class actionhelper dedicated for direct communication between native programs and JS, including the following features: Add favorites, set the page title, disable the current activity

Package COM. souapp. token Ke. yuer. JS; import android. app. activity; import android. OS. handler; import android. util. log; import android. webKit. webview; import COM. souapp. token Ke. yuer. DB. dbfavoriteopeator; import COM. souapp. token Ke. yuer. exception. dataisexistexception; import COM. souapp. token Ke. yuer. favorite. favoritebean; import COM. souapp. common. tools. datemedils;/****** handle js to actively call its own method * @ author tester **/public class actionhelper {private string tag = "actionhelper"; private activity cxt; private webview; private string callbackfunction; // bar code scan result, private actionhelper () {} Private Static actionhelper instance; private handler; private string result = "added to favorites successfully. "; public static actionhelper getinstance () {If (instance = NULL) {instance = new actionhelper ();} return instance;} public void setvalue (activity context, webview WV, handler ha) {cxt = context; webview = WV; handler = ha ;} /***** call back the scan result to js * @ Param data */Public void savebarcodescandata (string data) {try {webview. loadurl ("javascript:" + callbackfunction + "('" + Data + "')");} catch (exception e) {log. E (TAG, "", e) ;}/ ***** set the page title * @ Param name */Public void setshortketitle (final string name) {try {handler. post (New runnable () {public void run () {// call the client setcontactinfo method webview. loadurl ("javascript: setjavasketitle ('" + name + "')") ;}}) ;}catch (exception e) {log. E (TAG, "", e) ;}/ ***** call the search page to view local detailed articles * @ Param savepath */Public void viewdetail (final string savepath) {try {log. D (TAG, "========== viewdetail ==========");} catch (exception e) {log. E (TAG, "", e) ;}finally {handler. post (New runnable () {public void run () {// call JS and display the operation status webview. loadurl ("file: // android_asset/static_mobile_baike" + savepath );}});}} /***** add articles to favorites * @ Param name */Public void AddFavorite (final String title, final string category, final string tag, final string savepath) {try {log. D (TAG, "========== AddFavorite ========"); string savedate = datatils. formatlong2str (system. currenttimemillis (); favoritebean = new favoritebean (); bean. settitle (title); bean. setcategory (category); bean. settag (TAG); bean. setsavepath (savepath. substring (1); bean. setorder (0); bean. setsavedate (savedate); dbfavoriteopeator. savefavorite (cxt, bean); Result = "added to Favorites";} catch (dataisexistexception E1) {log. E (TAG, "", E1); Result = "prompt:" + e1.getmessage ();} catch (exception e) {log. E (TAG, "", e); Result = "error:" + E. getmessage ();} finally {handler. post (New runnable () {public void run () {// call JS and display the operation status webview. loadurl ("javascript: callback_echomsg ('" + Result + "')");}});}} /***** JS call to close activity * @ Param mother */Public void exitactivity () {try {If (cxt = NULL) return; cxt. finish ();} catch (exception e) {e. printstacktrace () ;}/ ***** call the barcode scan interface */Public void startbarcodescanui (string URL, string invokefunction) {/* try {log. E (TAG, "Start URL:" + URL); callbackfunction = invokefunction; intent it = new intent (); it. setclass (cxt, zxingscanneractivity. class); it. putextra ("queryurl", URL); // pass the requested URL to the page cxt scanned. startactivity (it);} catch (exception e) {e. printstacktrace ();}*/}}

Directory Browsing: When a user clicks a category on the home page (for example, parenting encyclopedia), I will load a category display page through webview, and then the user clicks the operation on the category display page, the webpage jumps through HTML relative links. On the classification display page, there is a "return home page" button, which uses js to call the native program to control and disable webview activity.

This "back to the home page" is where JS calls the native code, and another operation is where the native calls the JS Code: The page title, it is uploaded to webpageactivtiy based on the classification of the main interface and then displayed on the HTML5 page.

The Code is as follows:

The native code looks at the setjavasketitle method in actionhelper. Java above, and then we look at the JS Code as follows:

Set the JS Code of the encyclopedia article title:

<script type="text/javascript">  function setBaikeTitle(name){    console.log("setTitle:"+name);    //$("#baike_title").html(name);    document.getElementById("baike_title").innerHTML=name;  }</script>

Closes the JS Code of the activity.

<SCRIPT type = "text/JavaScript"> // bind an event listener to the button $ (document ). BIND ('pageinit', function () {$ ('# Goback '). BIND ('tap', function (e) {// call the phone to close the home page if (window. es) {window. es. exitactivity (); console. log ("close current encyclopedia page"); Return ;}}) ;}); </SCRIPT>

Here, ES is the object that actionhelper exposes to webview and can be called to view the definition code of webview in webpageactivity:

 
WebView wv = (WebView) this.findViewById(R.id.webview);
Websettings settings = WV. getsettings (); settings. setjavascriptenabled (true); settings. setallowfileaccess (true); WV. setscrollbarstyle (view. scrollbars_inside_overlay); souapp_url = "file: // android_asset/static_mobile_ke ke/"; // first, judge whether it is a directory or a favorite article. String optional ke_article = getintent (). getextras (). getstring ("incluke_article"); If (incluke_article! = NULL) {// directly open the page souapp_url + = baike_article + "? Pageid = 1 "; log. D (TAG, "page:" + souapp_url);} else {// use directory mode string export ke_type = This. getintent (). getextras (). getstring ("incluke_type"); souapp_url + = incluke_type + ". html "; baike_name = This. getintent (). getextras (). getstring ("baike_name");}/***** register the JS call method ***/AH = actionhelper. getinstance (); Ah. setvalue (this, WV, new handler (); WV. addjavascriptinterface (ah, "es"); WV. loadurl (souapp_url); WV. setbackgroundcolor (0); WV. setbackgroundresource (R. drawable. loadpage );

Here, I omit some code, such as displaying the webpage loading progress;

Let's take a look at the HTML5 Page code:

<! -- Home --> <Div data-role = "page" id = "main_page" data-dom-Cache = "true"> <Div data-theme = "A" data-Role = "Header" data-position = "fixed"> <a id = "Goback" data-rel = "back" data-role = "button" data-Icon = "back"> back to the home page </a> 

If the ID is Goback, It is the return button and the ID is javaske_title. The innerhtml content will be replaced.

Here we will not talk about how Android webview communicates with Js. The principle is very simple. If you don't understand it, you can check the article and read it again.

Favorites browsing:

All of the collected encyclopedia articles are displayed here. I use the sqllite database to store it on my mobile phone;

The "delete" Operation on the interface is a native code operation. clicking each line is to view the article page operation. In fact, webpageactivity is called to load

file:///android_asset/static_mobile_baike/  

The document page under the directory.

Encyclopedia search:

Full-text searches of over 20 mb of data can only be placed on the server; Chinese Word Segmentation and indexing are not described here. The principle is that users enter keywords, an HTML5 page is returned through the server;

At this time, the user can view the detailed page and directly call the static page display on the mobile phone.

Let's talk about the pitfalls of jquery mobile.:

It is not too difficult to say it is a pitfall. Mobile phones under Android 4 feel slow, mobile phones above Android 4 are generally at a high speed, and iPhone phones are acceptable for use, and the experience is okay;

The use of data-Ajax = "false" can solve the problem of flash screen, but the status of the last opened page cannot be recorded, I used Ajax when my screen was made too speechless. Some people may ask what is a pop-up screen?

You just need to click a button or link to flash the page 1 ~ Switch is started only twice.

<A data-Ajax = "false" href = ". /baike_type_4__category_4.html "data-Cache =" true "data-role =" button "data-theme =" B "> pre-pregnancy </a>

Use jquery moblie to debug the HTML page in the browser before embedding webview.Webview debugging is not very convenient.


Finally, if you have exchange, you can add my Sina Weibo: http://weibo.com/changeself

LiBo parenting Encyclopedia: http://liboapp.com

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.