ANDROID+HTML5 hybrid development of imitation micro-trust friend Circle _android

Source: Internet
Author: User
Tags mixed jquery library

Before development
about the beginning of last year, it may be the Html5 of fire, it is not ... Can always hear from the Internet to the mixed development of XXX, in order to keep up with the trend (although a bit late), we also look at ANDROID+HTML5 mixed development is what!
Today's case is the micro-letter of the Circle of friends, because I think it is a micro-letter to H5 to "red." But warn you said in the front, our imitation circle of friends but "low imitation", but the mixed development of the general Flow said that the interface may be unsightly ... Excuse me..

Development environment
Android Studio 2.2.2
JDK1.7
API 24
Gradle 2.2.2
JQuery v3.1.1

Related knowledge points
the use of WebView
JSON parsing and generation (using Gson in this case)
HTML and JS Basics (for convenience, this case uses jquery)
Java and JS interaction

I think the above Android knowledge points should not be difficult for everyone. In H5 and JS aspects I understand is not particularly in-depth, will use the basic is enough.

Start developing
Case Preview
above said, please forgive the interface of unsightly ....

Case analysis
Said mixed development, in fact, is to display the local HTML file on the WebView, so we want to solve the problem is how to transfer the Java data to the HTML file and through JS dynamic display.

In this case, the idea is to generate JSON data in the activity (these JSON data are fake data, in the project can get the JSON data directly from the network), JSON data through the interaction with JS, in JS received messages, Then the dynamically generated HTML item is displayed on the WebView! And each item has a corresponding Click event, click Back to the Android system toast, pop-up current click content.

Build a layout

Amount of ... It's actually a webview.

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "android:orientation="
  xmlns: Android= "http://schemas.android.com/apk/res/android"
  xmlns:tools= "Http://schemas.android.com/tools"
  Android:id= "@+id/activity_main"
  android:layout_width= "match_parent"
  android:layout_height= "Match_" Parent "
  tools:context=" com.lulu.weichatfriends.MainActivity ">
  <webview
    android:id=" @+id/ Main_web_view "
    android:layout_width=" match_parent "
    android:layout_height=" match_parent "/>
" </LinearLayout>

Entity class preparation

Used in this example to encapsulate JSON data

public class Friendszone {
  private String name;
  Private String icon;
  Private String content;

  Getter and setter ...
}

JS Support Class

This class is used to interact with JS.

/**
 * Created by Lulu on 2016/10/27.
 * JS Support class * * Public
class Jssupport {
  private context mcontext;
  Private String JSON;

  Public Jssupport {
    Mcontext = context;
  }
  public void Setjson (String json) {
    This.json = json;
  }

  @JavascriptInterface public
  String Getjson () {return
    json;
  }

  @JavascriptInterface public
  void Showtoast (String str) {
    toast.maketext (mcontext, str, toast.length_short) . Show ();
  }


@JavascriptInterface This note, this method can be invoked in JS.
The above two methods in the code, in the following JS can be called through the window.
This two method just can demonstrate, Java to JS pass data and JS return data to Java code

WebView's Preparation
the use of WebView has a lot to pay attention to, let's take a step-by-step:

Step1: initialization of webview in activity

Mwebview = (webview) Findviewbyid (R.id.main_web_view);
Resolution Click Link Jump Browser Problem
mwebview.setwebviewclient (new Webviewclient ());
JS support
websettings settings = Mwebview.getsettings ();
Settings.setjavascriptenabled (true);
Allow access to assets directory
settings.setallowfileaccess (true);
Set the WebView typesetting algorithm to achieve a single display, not allowing lateral movement of
settings.setlayoutalgorithm (WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
Assets file path
String path = "file:///android_asset/index.html";
Add JSON Data
Addjson ();
Load HTML page
mwebview.loadurl (path);

The path of the Note:assets file you don't have to say it later.
The Addjson () method above will then say

Step2: Addjson () method to generate JSON data to the Jssupport class

private void Addjson () {
  Jssupport jssupport = new Jssupport (this);
  list<friendszone> zones = new arraylist<> ();
  for (int i = 0; i < i++) {
    zones.add ("deer" + I, "images/icon.png", "Here is the HTML test data, here is the HTML test data, this Inside is the HTML test data "+ i)");
  }
  Gson Gson = new Gson ();
  String JSON = Gson.tojson (zones);
  LOG.D (TAG, "Addjson:json =>" + json);
  Jssupport.setjson (JSON);
  Add JS Interactive interface, and indicate the name of the object in JS
  mwebview.addjavascriptinterface (jssupport, "weichat");
}

Note:json data passed to the Jssupport class, there will be a Getjson () method can be called JS, complete data transfer

step3: This step is a small detail, not much use for our case. When your page jumps, the user presses the return key to return to the previous page instead of quitting the entire activity
Overriding the Onbackpressed () method

@Override public
void onbackpressed () {
  if (Mwebview.cangoback ()) {
    mwebview.goback ();
  } else {
    super.onbackpressed ();
  }

HTML and JS parts
This place is a priority today, and next step is how to create HTML and JS files in the Android project.

Step1: Create the Assets folder in the Src/main directory, create the index.html file in the created folder (name free), and then create the file or folder you want, as shown

The Note:js directory is stored in the jquery library, don't forget to add.
Here we can explain the path = "file:///android_asset/index.html" in WebView; This is a fixed code format, which is written in the official document

Step2: Complete the index.html file to interact with the Android system data


<script>
  var json = Window.weichat.getJson ();
  var infos = eval (JSON);
  for (var i = 0; i < infos.length i++) {
    info = infos[i];
    var img = Info.icon;
    var userName = info.name;
    var content = info.content;
    $ ("#head_background"). After ("<div ><div id= ' nav ' ></div><div id= ' info ') ><div id= ' userName ' > "+ userName +" </div><p id= ' content ' > "+ content +" </p></div>< /div> ");
    $ ("#userName"). Click (
      function () {
        var str = $ (this). text ();
        Window.weichat.showToast (str);
      }
    )
    $ ("#content"). Click (
      function () {
        var str = $ (this). text ();
        Window.weichat.showToast (str);
      }
    )
  }
</script>

Note: Here I only list some of the core code, the CSS style is not on the top.
In fact, the file is mainly using JS to implement dynamic Add item and to the corresponding item set up listening ...

This case code is combed.

Complete code

Code has been uploaded to GitHub, welcome everyone clone.

Summarize

See at the end everyone might think about what mixed development this is not so easy! Amount of ... Look is not difficult, after all I This is only demo, simple data transfer. Hope to be a guide to the great God. You are welcome to correct and revise this article.

Thank you for the share of the author of Jane's book.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.