preface
Our knowledge review plan for the weekly practice at 📖 is continuing. The theme of this week is “Hybrid APP”, which has a lot of content and a relatively long length, and each knowledge point has a lot of content.
Previously shared weekly content, I have sorted into the nuggets collection 📔 “EFT Every Monday practice” on the, welcome to click on the collection 💕💕.
Note: this article collates the source network, some pictures/paragraphs can not find the original source, if there is infringement, contact delete.
I. What is Hybrid App and what is the difference between it and Native App and Web App
Reference article:
-
“Differences between Web Apps Hybrid Apps and Native Apps”
-
Analysis and Comparison of Native, Hybrid, React Native and Web APP Solutions
1.1 Mainstream Application types
With the rapid development of mobile Internet, the current mainstream mobile applications on the market are mainly divided into three categories: Web App, Native App and Hybrid App.
The general relationship among the three is as follows:
1.2 Web App
Web App, namely mobile website, generally refers to web-based application, which is run based on browser and does not need to download and install. Basically, it can be said to be a touch screen version of Web application. These apps are basically a web page or series of web pages designed to work on mobile screens.
Web sites generally fall into two categories:
-
MPA(Multi-page Application)
-
SPA(Single-page Application)
A general Web App is a website developed in the form of a SPA.
Advantages:
- Low cost of development and maintenance, cross-platform, easy debugging;
Front-end staff development of the code, can be applied to major browsers (special cases can be compatible with the code), no new learning costs, and can be directly in the browser debugging.
- Update the fastest;
Since Web App resources are deployed directly on the server side, user access is updated by simply replacing the server-side files (some caching issues need to be addressed, of course).
- No need to install App, will not occupy the phone memory;
It can be accessed through a browser, no installation is required, and the user cost is lower.
Disadvantages:
- Low performance and poor user experience;
Because it is directly accessed through the browser, it cannot use the native API, and the operation experience is not good.
- Depending on the network, the page access speed is slow and the traffic is consumed;
Web App must rely on the network for each access and load resources from the server. When the network speed is slow, the access speed is not ideal, especially on the mobile end, which requires high website performance optimization.
- Limited function, a large number of functions can not be realized;
You can only use some special APIS of HTML5, you can’t call the native API, so many functions can’t be implemented.
- Temporary entrance, low user retention rate;
This is both a strength and a weakness. The strength is that there is no installation required, and it is sometimes difficult to find after you have used it, or it is difficult to reserve an entry for a Web app, making it difficult for users to use it again.
1.3 Native App
Native APP refers to the Native program, which needs to be downloaded, installed and used by users. Generally, it relies on the operating system and has strong interaction. It is a complete APP with strong extensibility and can be released in the APP store.
Currently, the mainstream platforms in the market are: Android and iOS.
Advantages:
-
Directly relying on the operating system, good user experience, smooth operation, stable performance;
-
High retention;
-
The most powerful function, especially in the interaction with the system, almost all functions can be realized;
Since Native APP is directly based on the system, it can directly call the API provided by the official, with the most comprehensive functions (such as local resource operation, notification, animation, etc.).
Disadvantages:
- The cost of development and maintenance is high, and it cannot be cross-platform, so each platform needs to develop independently.
Java based development on Android, OC or Swift based development on iOS, independent of each other, must have their own developers.
- High threshold, native personnel have a certain threshold of entry, less talent;
A big feature of native is independence, so it is not easy to get started, and Android and iOS need to learn independently.
- High distribution costs, slow updates, especially after launching the app store, waiting for the approval cycle;
Native app update is a big problem. In Android, the whole package of APK can be downloaded directly for update, but in iOS, if you release AppStore, you must update the AppStore address, and every update needs to be reviewed, so timely update cannot be achieved.
1.4 Hybrid App
Hybrid App refers to Hybrid development, that is, semi-native and semi-Web development mode, with cross-platform effect. Of course, in essence, the final release is still independent native App (various platforms have various SDKS).
Advantages:
- Low cost of learning and development, cross-platform, easy debugging;
Under Hybrid development mode, unified API is provided for JS invocation by native, and the actual main logic is completed by HTML and JS, and finally displayed in webView. In this way, only a set of code is required to achieve cross-platform effect, and debugging can be directly in the browser, which is very convenient.
In general, Hybrid can cross at least three platforms: Android App, iOS App and ordinary WebKit browser.
Front-end staff need to pay attention to some native API, the specific implementation does not need to care, there is no new learning content.
- Low maintenance costs, reusable functions, and easier to update;
Although it is not as fast as web app update, Hybrid can also provide API through native to actively download resources, so as to achieve the effect of only updating resource files without updating APK (IPA).
- The function is more complete, the performance and experience is much better than web app;
Because native apis can be called, many functions can be implemented as long as they are provided natively, and performance is relatively close to native.
- Some pages with performance requirements can be implemented natively;
This mode is the native hybrid Web, so we can completely use the strong interaction, high performance requirements of the page written in the native, and then some other pages written in JS, embedded in the WebView, to achieve the best experience.
Disadvantages:
- Compared with the original, the performance is still greater loss;
This mode is limited by the performance of the WebView, there is a lot of wear and tear compared to native, the experience is not comparable to native.
- Not suitable for highly interactive apps;
This mode is mainly applicable to some news reading and information display apps, but not to some apps with strong interaction or high performance requirements (for example, it is not suitable for many animations).
1.5 Differences among the Three
Comparison of the three use scenarios:
Comparison of technical characteristics of the three:
Add ReactNative together for comparison.
NativeApp | WebApp | HybridApp | ReactNativeApp | |
---|---|---|---|---|
Native feature experience | good | poor | good | Close to the good |
Rendering performance | Very fast | slow | Close to fast | fast |
Whether device low-level access is supported | support | Does not support | support | support |
Network requirements | offline | Relying on the network | Support offline (resources stored locally) | offline |
Update complexity | High (almost always updated via the App Store) | Low (server side direct update) | Low (resource pack updates are available) | Low (resource pack updates are available) |
A programming language | Android (Java), iOS (OC)/Swift | js+html+css3 | js+html+css3 | Mainly written in JS, syntax rules JSX |
Community resources | Rich (Android, iOS learning separately) | Abundant (lots of front-end resources) | Limitations (different hybrids are independent of each other) | Rich (unified active community) |
To fit the difficulty | Difficult (different platforms need to learn separately) | Simple (write once, support different platform access) | Simple (write once, run on any platform) | Medium (learn once, write on any platform) |
The development cycle | long | short | The shorter | medium |
Development costs | expensive | cheap | cheaper | medium |
cross-platform | Not cross-platform | All H5 browsers | Android, iOS, H5 browser | Android, iOS |
APP released | AppStore | The Web server | AppStore | AppStore |
1.6 How to choose the three
Here is a brief introduction of several cases, specific or to the actual project technical assessment results.
- Cases of pure Native App mode:
High performance requirements, excellent experience requirements, not the pursuit of development efficiency.
- Choosing Web App mode:
It does not pursue user experience and performance. There is no requirement for offline access. Normally, if you pursue performance and experience, you will not choose Web app.
- The Hybrid App mode is selected
In most cases, this mode is recommended for apps. This mode can be used to realize the interface with high requirements. For some general and display pages, it can be completely realized by Web to achieve cross-platform effect and improve efficiency. Hybrid solutions, which are generally better, keep resources locally to reduce network traffic consumption.
- React Native App mode
The pursuit of performance, experience, and the pursuit of development efficiency, and a certain amount of technical capital, willing to early investment.
React Native is expensive to learn, so it takes a lot of initial investment to reach a good level. However, when it reaches a certain level, its advantages are reflected in its development. Its performance is as good as that of the original, and its development speed is also fast
What is Cordova and what are its strengths and weaknesses
Reference Article: On the Framework of Cordova
2.1 introduction of Cordova
Cordova is a fast development platform for creating cross-platform mobile applications based on HTML, CSS, and JavaScript. It allows developers to leverage the core features of smartphones like iPhone, Android, Palm, Symbian, WP7, Bada, and Blackberry — including geolocation, accelerators, contacts, sound, and vibration.
It can also be used to develop plug-in interfaces between native and WebView components.
Source: Cordova is an open source project that PhoneGap contributed to Apache. It is the core code extracted from PhoneGap and the core engine that drives PhoneGap. Think of their relationship as similar to Webkit and Google Chrome.
2.2 Architecture diagram of Cordova
Architecture Diagram Introduction:
- Web App
It is used to store the code of our program, including business logic, as well as some resources needed for running (such as CSS, JavaScript, images, media files, etc.). The application is implemented through a Web page, the default local file name is index.html, and the application is executed in a WebView wrapped around the native application that you distribute to the app store.
- WebView
Cordova uses webViews to provide a complete user interface for applications that are a mix of WebViews and native application components.
- Cordova Plugins
Plugins are an important part of the Cordova ecosystem. It provides an interface for Cordova to communicate with native components and binds to a standard device API that allows you to call native code through JavaScript.
2.3 the advantages and disadvantages
Advantages:
- Cross-platform, simple development, low learning cost;
- More framework, more plug-ins, can be customized plug-ins;
- The earliest development, rich community resources;
Disadvantages:
- When the performance of WebView is low, the user experience is poor and the response is slow.
- Few Chinese document resources;
- Debugging is inconvenient, neither as good as native debugging, nor as pure Web debugging;
What is the mechanism of Cordova
Cordova plug-ins are add-ons that provide JavaScript interfaces to native components that allow your App to use native device capabilities beyond pure Web apps.
The implementation principles of Cordova on iOS are as follows:
3.1 Workflow
- Cordova makes native requests:
cordova.exec(successCallback, failCallback, service, action, actionArgs);
// successCallback: successful callback method
// failCallback: failed callback method
// server: the name of the service to be requested
// action: specifies the service action to be requested
// actionArgs: Parameters of the request action
Copy the code
-
Instead of passing these parameters directly to native Cordova, the JS side of Cordova does the following:
- Generate a unique identifier for each request (
callbackId
) and pass it to the native end. After processing, the native end will send thecallbackId
Together with the processing results returned to the JS side; - In order to
callbackId
为key
.{success:successCallback, fail:failCallback}
为value
Save the key-value pair in the dictionary on the JS side.successCallback
与failCallback
These two parameters do not need to be passed to the nativecallbackId
, the JS side can be based oncallbackId
Find the callback method; - For each JS request, the final data sent to native includes:
callbackId
.service
.action
.actionArgs
;
- Generate a unique identifier for each request (
-
When the native code gets the callbackId, Service, Action, and actionArgs, it does the following:
- According to the
service
Parameter to find the corresponding plug-in class; - According to the
action
Parameter to find the corresponding processing method in the plug-in class, and theactionArgs
As part of the processing method request parameters; - After processing, the processing results and
callbackId
Return to the JS side, the JS side will receive according tocallbackId
Find the callback method and pass the processing results to the callback method;
- According to the
- JS end according to
callbackId
The callbackcordova.js
// Find the callback method based on the callbackId and success flag, and pass the processing result to the callback method
callbackFromNative: function(callbackId, success, status, args, keepCallback) {
var callback = cordova.callbacks[callbackId];
if (callback) {
if (success && status == cordova.callbackStatus.OK) {
callback.success && callback.success.apply(null, args);
} else if(! success) { callback.fail && callback.fail.apply(null, args);
}
// Clear callback if not expecting any more results
if(! keepCallback) {deletecordova.callbacks[callbackId]; }}}Copy the code
4. What is JS Bridge and what is its function
Reference article: Principles of JSBridge
4.1 Introduction to JS Bridge
To put it simply, JSBridge mainly provides an interface for JavaScript to invoke Native functions, so that the front-end of mixed development can conveniently use Native functions such as address location, camera and even payment.
JSBridge, just like the meaning of “Bridge” in its name, is a Bridge between Native and non-native. Its core is to build a message communication channel between Native and non-native, and it is a two-way communication channel.
JSBridge is also known as Hybrid App technology.
A channel of so-called two-way communication:
- JS sends a message to Native:
Call relevant functions and notify Native of the relevant status of the current JS.
- Native sends a message to JS:
Recall the call result, message push, and notify the current state of JS Native.
4.2. Implementation principle of JS Bridge
Reference article: “Hybrid APP Basics (iv)- JSBridge Principle”
JSBridge for Android and iOS
4.2.1 Basic process
- The H5 page somehow triggers one
url scheme
; - Native to capture
url scheme
, and analyze and process; - Native calls H5’s JSBridge object to pass the callback;
Native WebView/UIWebView controls can already communicate with JS data, so why JSBridge?
There are many reasons for using JSBridge:
- Android4.2 the following,
addJavascriptInterface
There are security lapses in the way. - JS cannot call Native under iOS7.
url scheme
Interactive mode is a set of existing mature solutions that can be perfectly compatible with various versions, compatibility with previous versions of technology.
4.2.1 Implementation Process (Android as an example)
- To formulate the protocol, refer to the PROTOCOL formulated by HTTP:
jsbridge://className:port/methodName? jsonObj
;
ClassName // The name of the class that the Android implementation exposes to the front end port // The port that Android returns the result to the front end methodName // The function that the front end needs to call jsonObj // The parameter that the front end passes to AndroidCopy the code
- Create a new HTML file named
index.html
, write abutton
The bindingclick
Events;
<button onclick="JSBridge.call( 'bridge', 'showToast', {'msg':'Hello JSBridge'}, function(res){ alert(JSON.stringify(res)) } )">Test showToast</button>
Copy the code
- Create a new JS file named
JSBridge.js
, in step 2JSBridge.call
Is the callJSBridge.js
In thecall
Method, followed by four parameters;
call: function (obj, method, params, callback) {
console.log(obj+""+method+""+params+""+callback);
var port = Util.getPort();
console.log(port);
this.callbacks[port] = callback;
var uri=Util.getUri(obj,method,params,port);
console.log(uri);
window.prompt(uri, "");
},
Copy the code
The call method in jsbridge. js finally calls the window.prompt method, which triggers the Android webChromeClient callback.
window.prompt
triggeredWebChromeClient
(This requires a functionWebView.setWebChromeClient
(new WebChromeClietn()
) to set);
Class for the following callback onJsPrompt. At this point, the communication between the front end and the Android side is complete, because the information of the front end is smoothly passed to the Android through this function.
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
result.confirm(JSBridge.callJava(view,message));
return true;
}
Copy the code
- Android defines a class
JSBridge.java
To manage functions exposed for use by the front end;
This class has two functions:
- Dynamic registration of functions exposed to the front end.
- Parses the front-end information and calls the corresponding function on the Android side. In this example, it is:
showToast
Function.
Parses the information about the front end to get the function name called by the front end:
Uri uri = Uri.parse(uriString);
className = uri.getHost();
param = uri.getQuery();
port = uri.getPort() + "";
String path = uri.getPath();
HashMap< String, Method> methodHashMap = exposedMethod.get(className);
Method method = methodHashMap.get(methodName);
Copy the code
Call the showToast function on Android by obtaining the function name, in this case showToast.
method.invoke(null,webView,new JSONObject(param),new Callback(webView,port));
Copy the code
- Define the class
BridgeImpl.java
To concretely implement all the functions exposed to the front end. Here,showToast
The function is as follows:
public static void showToast(WebView webView, JSONObject param, final JSBridge.Callback callback){
String message = param.optString("msg");
Toast.makeText(webView.getContext(),message,Toast.LENGTH_LONG).show();
if(null! = callback){try {
JSONObject object = new JSONObject();
object.put("key"."value");
object.put("key1"."vaule1");
callback.apply(getJSONObject(0."ok",object));
}catch(Exception e){ e.printStackTrace(); }}}Copy the code
5. Please list the implementation methods of JS Bridge under Android and iOS platforms
There’s a lot of code here, so I’m going to use a picture to show it, so you can zoom in and see it.
5.1 Implementation of Android
5.1.1 Two ways for Android to Invoke JS
- through
WebView
theloadUrl()
:
The JS code call must be called after the onPageFinished() callback, otherwise it will not be called.
Web side code:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>The front-end code</title>
<script>
// The method Android needs to call
function callJS(){
alert("Android calls the JS callJS method.");
}
</script>
</head>
</html>
Copy the code
Android code:
- through
WebView
theevaluateJavascript()
:
// Just change the loadUrl() of the first method to the following method
mWebView.evaluateJavascript(
"javascript:callJS()".new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
// This is the result returned by js}}); }Copy the code
5.1.2 Three ways for JS to call Android
- Object mapping via WebView addJavascriptInterface() :
Android mapping:
// Inherited from the Object class
public class AndroidtoJs extends Object {
// Define the method that JS needs to call
// Methods called by javascript must be annotated with @javascriptInterface
@JavascriptInterface
public void hello(String msg) {
System.out.println("JS calls Android's Hello method"); }}Copy the code
Web:
<! DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>The front-end code</title>
<script>
function callAndroid(){
// Because of the object mapping, calling the test object is equal to calling the Android mapping object
test.hello("Js calls the Hello method in Android");
}
</script>
</head>
<body>// Click the button to call the callAndroid function<button type="button" id="button1" "callAndroid() "></button>
</body>
</html>
Copy the code
The Android side:
- through
WebViewClient
的shouldOverrideUrlLoading ()
Method callback interceptionurl
:
Web side:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>The front-end code</title>
<script>
function callAndroid(){
/* The url protocol is: js://webview? arg1=111&arg2=222*/
document.location = "js://webview? arg1=111&arg2=222";
}
</script>
</head>
<! -- Click the button to call callAndroid () -->
<body>
<button type="button" id="button1"
onclick="callAndroid()"
>Click to invoke the Android code</button>
</body>
</html>
Copy the code
The Android side:
- Using WebChromeClient’s method callback to intercept the JS dialog method:
Intercept JS dialog box alert(), Confirm(), prompt() messages via WebChromeClient onJsAlert(), onJsConfirm(), onJsPrompt() callback.
Web side:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>The front-end code</title>
<script>
function clickprompt(){
Call prompt ()
var result=prompt("js://demo? arg1=111&arg2=222");
alert("demo " + result);
}
</script>
</head>
<! Click the button to call clickPrompt () -->
<body>
<button type="button" id="button1"
onclick="clickprompt()"
>Click to invoke the Android code</button>
</body>
</html>
Copy the code
The Android side:
5.2 iOS Implementation Mode
5.2.1 Two ways for JS to Invoke iOS
- use
XMLHttpRequest
How to initiate a request:
Web side:
XMLHttpRequest bridge:
Execxhr.open (‘HEAD’, “/! gap_exec?” + (+new Date()), true); The requested address is /! Gap_exec; And put the requested data in the request header, as shown in the code: execXhr. SetRequestHeader (‘ CMDS ‘, iOSExec nativeFetchMessages ()); .
On the Objective-C side, a subclass of NSURLProtocol checks each request if the address is /! Gap_exec is a request from Cordova, which is intercepted directly. After intercepted, the request data can be analyzed and distributed to methods of different plugin classes (subclasses of CDVPlugin) :
This method is preferred in Cordova. The comments in cordova. js explain why XMLHttpRequest is preferred and why the second iframe bridge is reserved:
// XHR mode does not work on iOS 4.2, So default to IFRAME_NAV for such devices. // XHR mode's main advantage is working around a bug in-webkit-scroll, Which // doesn't exist in 4.X devices anyways123Copy the code
The iframe bridge:
Create a transparent iframe on the JS side, set the SRC of the ifame to the custom protocol, and when the SRC of the ifame changes, UIWebView will its delegate callback webView: shouldStartLoadWithRequest: navigationType: method, key code is as follows:
- By setting transparent
iframe
的src
Properties:
5.2.2 How iOS invokes JS
UIWebView stringByEvaluatingJavaScriptFromString: one method, this method can make a UIWebView object to perform a JS code, Cordova uses objective-C to communicate with JS. Cordova uses objective-C to communicate with JS. Cordova uses this method in several ways.
- Get JS request data:
- Return the result of the JS request to the JS side:
conclusion
For the new mixed application development partners, these will be a little difficult, but a good understanding of the flow chart, and then a reason for thinking, I believe that will help 😁
Cheer everybody up ~~