Discussion on the interaction between mixed development and ANDROID,JS data

Source: Internet
Author: User

This article is the author original, such as reproduced please indicate the source!

I. INTRODUCTION

  现在时代已经走过了移动互联网的超级火爆阶段,市场上移动开发人员已经趋于饱和,显然,只会原生APP的开发已不能满足市场的需求,随着H5的兴起与火爆,H5在原生APP中的使用越来越广泛,也就是我们常说的混合开发(Hybrid APP).最新很火的小程序相信大家都是知道的,实际上小程序加载的界面就是一个HTML5的界面,HTML5界面在一些电商类的APP中主要承担展示数据的作用,但是他的作用并不仅限于此,最起码js调用原生方法和原生调用js的方法是必须的,我们看到的现在小程序中的膜拜单车入口,进入后的扫码功能,就是js调用安卓原生的摄像头进行扫码的,另外分享功能以及点击js中的一个按钮跳转到APP原生界面这些需求都是很常见的,所以js和原生方法的相互调用是必须会的.最近做HTML5相关的地图APP,正好用到了相关的知识,总结下项目中遇到的坑.

Two. js interacting with Android

1.Android How to load a H5 interface to the app?
At present, the more mature solution is to use the Android packaged middleware WebView.

Load mode

//创建一个WebView,也可以直接在布局中写WebView控件new WebView(mContext);//加载网络上的一个urlString"https://www.baidu.com";mWebView.loadUrl(url);//加载本地的一个url,asserts目录下的mWebView.loadUrl("file:///android_asset/index.html");

Some important settings for WebView

//Get to WebSettings control class firstWebSettings settings = Mwebview.getsettings ();//Set support JavaScriptSettings.setjavascriptenabled (true);//set to False to adjust the picture to fit the WebView sizeSettings.setusewideviewport (false);//settings can access filesSettings.setallowfileaccess (true); Settings.setallowcontentaccess (true); Settings.setallowfileaccessfromfileurls (true);//Set JS support databaseSettings.setdatabaseenabled (true);//Set JS support Window.localstorage, if not set, JS gets the window and localstorage are null, before I was the pit, the project JS interface used to Window.localstorage, Then I and JS use alert way debugging process, found that this method has been an error to find this API.Settings.setdomstorageenabled (true); Mwebview.loadurl ("File:///android_asset/index.html");//Add a Java and JS interactive interface, Android string equivalent to a Brige bridge, Android 4.2 added @javascriptinterface interface, Only the Code @javascriptinterface annotated method JS can be called, before the class is injected and all the public methods inherited from the parent class can be accessed, which is to further ensure the security of the app.Mwebview.addjavascriptinterface (Msnmap,"Android");//Set WebView whether to load the completed listenerMwebview.setwebviewclient (NewWebviewclient () {@Override            //webview The method that is called when the load completes             Public void onpagefinished(WebView view, String URL) {Super. onpagefinished (view, URL); }@Override            //webview Start loading the calling method             Public void onpagestarted(WebView view, String URL, Bitmap favicon) {Super. onpagestarted (view, URL, favicon);@Override            the method called when the//webview interface is visible             Public void onpagecommitvisible(WebView view, String URL) {Super. onpagecommitvisible (view, URL); }@Override            //whether to intercept the JS and Java call methods             Public Boolean shouldoverrideurlloading(WebView view, webresourcerequest request) {return true; }        });//This setting ensures that the system's browser is automatically invoked when the interface is loaded, rather than prompting users to choose which browserMwebview.setwebchromeclient (NewWebchromeclient () {//corresponding to the alert () method in JS, you can override this method to complete the interaction with JS.            @Override             Public Boolean Onjsalert(WebView view, string URL, string message, jsresult result) {return Super. Onjsalert (view, URL, message, result); }//corresponding JS in promt (), you can override this method to complete the interaction with JS            @Override             Public Boolean onjsprompt(WebView view, string URL, String message, string defaultvalue, jspromptresult result) {return Super. onjsprompt (view, URL, message, defaultvalue, result); }///corresponding to JS in the Console.log method, you can rewrite the method to complete the interaction with JS            @Override             Public Boolean Onconsolemessage(Consolemessage consolemessage) {return Super. Onconsolemessage (Consolemessage); }        });

Java method of invoking JS

//比如我要调用addline(jsonline)方法,这里给出我写的一个示例//WebView规定java和js交互的时候前面的字段是javascript:+方法名//注意:传变量的时候注意要给字符串加上两个单引号,传递方式就是我下面写的那种规范publicvoidaddLine(Line line) {        ifnull) {            jsonLine = mGson.toJson(line);            mWebView.loadUrl("javascript:addLine(‘""‘)");        }    }

JS method to call Java

//Introduce one of the simplest ways, of course, you can use the pseudo-protocol to encapsulate//1. Add an interactive interface, Msnmap represents the Java class to inject, Android is a bridging string, and the use of JS calls is used to interact with this stringMwebview.addjavascriptinterface (Msnmap,"Android");//2. Called in JS, such as a method to invoke local read binary files@JavascriptInterface PublicStringReadshape(String Mapshape) {Gson Gson =NewGson ();        Mapshape Mapshape = Gson.fromjson (Mapshape, Mapshape.class);        String shapeBase64 = Seinterfacepvreader.getmapshape (Mapshape); System. out. println (SHAPEBASE64);returnShapeBase64; }//3.js Call and get the return value, in addition to explain, JS call Java method is in the webview of a separate background thread, and here JS call Android method when passing parameters can only pass one, and Java and JS interaction method is not support binary stream interaction, only support simple basic data types, such as int,boolean,string, arrays are not supported, arrays can be in the form of a JSON stringvarBufferdata = Android.readshape (JSON);

Three. Data structure, file read

文件读取这块内容,因为矢量数据的存储结构不是我们公司的人设计的,是和我们公司合作的人设计的,他们的服务器代码采用的是C++结合lua脚本语言共同编写的,涉及到数据结构的具体详情不变透漏,主要说下C++和java数据结构的差别以及读取数据时选择的API.

Char in 1.c++ and Char in Java
Char in C + +, like char in iOS object-c, takes up a byte
Char in Java accounts for 2 bytes
So in the process of data reading, C + + often creates a vector buf equivalent to the byte array created when reading a file in Java. Here is a tool class for the int to byte array in Java.

//specific use of high to low or low to high depending on the data structure   Public Static byte[]Inttobytearray(inti) {byte[] result =New byte[4];//From high to low//result[0] = (byte) ((I >>) & 0xFF);//result[1] = (byte) ((I >>) & 0xFF);//result[2] = (byte) ((I >> 8) & 0xFF);//result[3] = (byte) (I & 0xFF);        //Low in front        //From low to highresult[0] = (byte) (I &0xFF); result[1] = (byte) ((I >>8) &0xFF); result[2] = (byte) ((I >> -) &0xFF); result[3] = (byte) ((I >> -) &0xFF);returnResult }/** * byte[] converted to int[], low in the previous way * @param title * @return  */     Public Static int[]Bytearraytointarray(byte[] title) {int[] Array =New int[Title.length/4];byte[] temp =New byte[4];intK =0; for(inti =0; i < title.length; i++) {Temp[i%4] = Title[i];if(I >0&& (i+1) %4==0) {Array[k] = ByteArrayToInt2 (temp);            k++; }        }returnArray }/** * byte array converted to int value of the tool class, low in front * * @param b * @return byte[] converted to int number */     Public Static int ByteArrayToInt2(byte[] b) {intMASK =0xFF;intresult =0; result = b[0] & MASK; result = result + ((b[1] & MASK) <<8); result = result + ((b[2] & MASK) << -); result = result + ((b[3] & MASK) << -);returnResult }

2. Read the file to select the Randomaccessfile class and the FileInputStream class
Two classes can be used to read the effect of binary files, while two classes have a way to navigate to a location in the file, but they are different.
The FileInputStream Skip () method is positioned relative to the current position.
The Seek () method of the Randomaccessfile can be positioned anywhere in the file
Here's a code for an example

fis.skip(10);fis.skip(5);//执行完这两行代码后读取的输入流FileInputStream定位到文件的第15个字节处raf.seek(10);raf.seek(5);//这两行代码的最终结果是RandomAccessFile最终定位到文件的第5个字节处.//另外需要注意的是:RandomAccessFile是继承于Object的,只是他实现了DataOutput, DataInput,所以可以读文件也可以写文件.而FileInputStream是继承于InputStream的,只能读文件,而我在项目中读文件采用的是InputStream读,ByteArrayOutputStream作为输出流存储数据.

How Java and JS interact with files
Java and JS are not support direct binary flow interaction, so we have to exchange a way to interact with the binary data after reading the use of the BASE64 algorithm into a string, the string is passed to the JS,JS and then using the BASE64 algorithm to deserialize the binary data stream. Except this way, of course, There are other ideas, such as mobile development of a local server to JS send a request to complete the data interaction.

Four. Project Summary

目前来说,原生与H5的混合开发相对比较成熟,但是现在没有任何一个工具能够在js与java之前完成debug调试,所以项目上遇到问题只能采用日志和alert弹框的方式一步一步排查代码中的错误,调试起来复杂又繁琐,而且java和js在数据交互上依赖浏览器内核,性能上也存在问题,希望不久的将来,技术上能够突破这些瓶颈.地图的开发还是使用原生调用c++的OpenGL绘制矢量地图比较靠谱,之前研究过1个月的OpenGL开发,因为太难以及项目进度比较赶的原因没有继续下去,接下来会抽出更多的时间去完成OpenGL的底层绘制地图,后续的博客也会分享OpenGL的学习之路.

I love the words, and June mutual encouragement: than you are smarter than you have to work harder, you have any reason not to work hard?

If there are deficiencies, please correct the comments, thank you!

Discussion on the interaction between mixed development and ANDROID,JS data

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.