Stock Liao information

— Basic knowledge of stocks|Introduction to basics of stocks|Stock learning|Basic knowledge of stocks

Build a WebAPP by integrating vue with WebView and JSBridge, taking scanning code as an example

Release Time:2022-06-10 Topic:daily limit background map Reading:73 Navigation:Stock Liao information > Technology > Android > Build a WebAPP by integrating vue with WebView and JSBridge, taking scanning code as an example phone-reading

Business Scenario:

Because the company's project includes the function of the mobile terminal, and the cooperation of hardware is required to complete the business, such as Bluetooth connection to printers, QR codes and other barcodes Scanning, it is definitely not suitable to write a webpage adapted to the mobile terminal in the past, but at present the team does not have a small partner who is proficient in using android for development, so a solution that can use mobile phone hardware and use webpage to develop mobile terminal is urgently needed.

The following solutions are proposed for this:

1. WeChat applet: It can use hardware capabilities, cross-platform, and easy to develop, but because our project is used on the intranet , so it was ruthlessly abandoned

      2. HTML+: launched by the HTML5 China Industry Alliance under the Ministry of Public Information, it looks very powerful and provides a large number of APIs for calling hardware capabilities, but because the documentation is too bad, the community does not seem to be good Ground, mainly because there is not so much time, I have to decide which solution to use within two days, and to build the framework, the cost of trial and error is too high, so I refuse, of course, I will not say it is because I am too stupid to learn, It looks pretty good, I will have time to study it later.

3. android's webView control: The bottom layer is the kernel of webkit, which can solve the communication problem between webView and native Android. Baidu has seen that webView is supported, and there are many It is a mature solution, so it was decided to use this method to build webApp at that time. The advantage of this method is that the technology is mature, there are many articles on the Internet, at least it won't fall out of the pit and can't climb out, it supports intranet use, can be packaged as an APP, and the style is improved a lot, and you can use html to write beautiful pages. Much simpler than native Android.

    There are many ways to package apk in html, but they are all the same. The way to use your own writing shell here is relatively uncomplicated, but the Android part is relatively controllable, not a black box, only The communication problem needs to be solved.

Technology stack:

android: not very familiar, know how to create projects, understand android Project structure, how controls interact with the activity.

  webView: The bottom layer of webView is the webkit kernel that drives, so you can think of this object as a window object in js.

JSBridge: A bridge between android and webView communication, android exposes method registration to js calls, and js registration to android calls

vue : Use vue to write pages, others can also be html.

Zxing: an open source code scanning framework


Initialize the page Click [Change WEBVIEW to blue] Click [Change WEBVIEW to red]

After scanning the code

Implementation steps: < /h1>

1. Create a new Android project (white background on the main interface, the one in the middle of hello world)

2. Add the relevant dependencies of JSBridge

Add in the project's [build.gradle]: maven { url "" }


Add in the [build.gradle] of the module: compile 'com.github.lzyzsd:jsbridge:1.0.4'


3. Add Zxing related dependencies, scan code plugin

I don't use it directly here, but use the packaged project, download it from GitHub and copy the zxing-lib folder


      copied to the root path of the current android project



Add in [build.gradle] of module: implementation project(':zxing-lib')

Modify [settings.gradle]

4. Configure Android's project manifest file [ app/src/main/AndroidMa nifest.xml], This file is used to describe the configuration information of Android, such as app name, main interface, permissions, etc.

5. The main interface of Android, using linear layout, the color inside is The constants used can be built by yourself in the resource file.

6. MainActivity, see the comments for details

package com.example.mywebapp;import android.Manifest;import android.content.Intent; import;import android.os.Bundle;import;import android.util.Log;import android.view.KeyEvent;import android.view.View;import android .widget.*;import com.github.lzyzsd.jsbridge.BridgeHandler;import com.github.lzyzsd.jsbridge.BridgeWebView;import com.github.lzyzsd.jsbridge.CallBackFunction;import;import;public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); /** Using JSBridge enhanced WebView * / private BridgeWebView mBridgeWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity _ main); /**Initialize*/ init(); } /**Initialize the page* / public void init() { /** Get the WebView control and configure it */ mBridgeWebView= (BridgeWebView) findViewById( _ bridge _ webView); /** Load the page in http mode, here you can also write Put the good page under the project and load it as a file */ mBridgeWebView.loadUrl(""); mBridgeWebView.getSettings().setAllowContentAccess(true); /** Whether to enable JS * / mBridgeWebView.getSettings().setJavaScriptEnabled(true); /** Register the method called by js*/ mBridgeWebView.registerHandler("scan", new BridgeHandler() { @Override public void handler(String data, CallBackFunction function) { / ** Scan code*/ start(); /** Parameters passed by js*/ Toast.makeText(MainActiv ity.this,"JS calls the parameters sent by scanning the code:" + data,Toast.LENGTH _ SHORT).show(); /** Execute the Android method and return the result to JS */ function.onCallBack("Processing , and return the result after processing"); } }); /** Click the button whose background is changed to blue*/ findViewById( View.OnClickListener() { @Override public void onClick(View view) { /** Call the function registered by html to modify the color, the value is blue */ mBridgeWebView.callHandler("updateBackColor","blue",new CallBackFunction(){ @Override public void onCallBack(String data) { Log.e (TAG, "Return data from web:" + data); } }); } }); /** Click the button with red background */ findViewById( View. OnClickListener() { @Override public void onClick(View view) { /** Call the function registered by html to modify the color, the value is red */ mBridgeWebView.callHandler("updateBackColor","red",new CallBackFunction(){ @Override public void onCallBack(String data) { Log.e( TAG, "Return data from web: " + data); } }); } }); } /** Start scanning code*/ private void start() { /** Apply for camera permission*/ if (ActivityCompat. checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION _ GRANTED) { /** Apply for permission*/ if (ActivityCompat.shouldShowReale(this, Manifest.permission.CAMERA)) { Toast.makeText(MainActivity.this, "Toast prompt message",Toast.LENGTH _ SHORT).show(); }, new String[ ]{Manifest.permission.CAMERA}, Constant.REQ _ PERM _ CAMERA); return; } /** Apply for file write permission*/ if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE _ EXTERNAL _ STORAGE)!=PackageManager.PERMISSION _ GRANTED){, new String[ ]{Manifest. permission.WRITE _ EXTERNAL _ STORAGE}, Constant.REQ _ PERM _ CAMERA); } /** Scan the QR code, call the registered Activity, the previously imported package has been written in it */ Intent intent = new Intent( MainActivit y.this, CaptureActivity.class); /** Start and identify the Activity, a unique identification is required at the end of the scan */ startActivityForResult(intent, Constant.REQ _ QR _ CODE); } /** * When other activities are enabled on the current page The callback that returns the result * @param re * @param resultCode * @param data */ @Override protected void onActivityResult(int re, int resultCode, Intent data) { super.onActivityResult(re, resultCode, data); /** scan result callback */ if (re == Constant.REQ _ QR _ CODE && resultCode == RESULT _ OK) { Bundle bundle = data.getExtras(); String scanResult = bundle.getString(Constant.INTENT _ EXTRA _ KEY _ QR _ SCAN); /** Display the scanned information*/ Toast.makeText(MainActivity.this,"scan result: " + scanResult,Toast.LENGTH _ SHORT).show(); TextView res = findViewById(; res.setText("The Android side displays the scan code result:" + scanResult); /** Call the function that receives the scan code end , the parameter is the scan code result*/ mBridgeWebView.callHandler("scanResult",scanResult, new CallBackFunction() { @Override public void onCallBack(String data) { Log.e("TAG","JS feedback result:" + data ); } }); } } private long exitTime = 0; /** * Monitor key events* @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { /** Listen to the fallback event, and click the fallback twice a second to exit the APP, otherwise just make the WebView fallback to the last accessed path*/ if (keyCode == KeyEvent.KEYCODE _ BACK && event.getAction() == KeyEvent.ACTION _ DOWN) { if (System.currentTimeMillis() - exitTime > 1000) { Toast.makeText(this, "Press again to exit the program",Toast.LENGTH _ LONG); exitTime = System.currentTimeMillis(); /** WebView fallback, same as the browser's fallback */ mBridgeWebView.goBack(); } else { finish(); System.exit(0); } return true; } return false; }}

android stuff just so More, let's take a look at the code on the mobile side.

------------------------------------------- -------------------------------- I am the dividing line------------- -------------------------------------------------- --------------

The key to the front end is not what to use to write the page, but to be able to use js to register in the calling function

7. Use JSBridge.js to call the android registration method or the registration method to call android, the writing method is relatively fixed, here only for Android, IOS also supports, the writing method is a bit different, there are many articles on the principle of JSBridge, interested in Baidu

/ /Execute callback function function setupWebViewJavascriptBridge(callback) { //If the object already exists, execute directly if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { //Otherwise add event listener and execute document.addEventListener( 'WebViewJavascriptBridgeReady' , function() { callback(WebViewJavascriptBridge) }, false ); }}//Register callback function setupWebViewJavascriptBridge(function (bridge) { //Initialize bridge.init(function (message, responseCallback) { var data = { 'Javascript Responds': 'Wee!' }; responseCallback(data); })})//Exposing the method of the current module export default { // js calls the APP method (parameters are: app provided The method name is passed to the data callback of the app) callHandler(name, data, callback) { setupWebViewJavascriptBridge(function (bridge) { bridge.callHandler(name, data, callback) }) }, // APP calls the js method (parameters are : method name callback provided by js) registerHandler(name, callback) { setupWebViewJavascriptBridge(function (bridge) { bridge.registerHandler(name, function (data, responseCallback) { callback(data, responseCallback) }) }) }}

8. How to use JSBridge on the page

Scan code current color: {{backColor}} HTML display scan result: {{code}} import $JSbridge from './JSbridge'export default { name: "JSBridgeTest", data( ) { return { backColor: 'black', code:'' } }, mounted() { //Execute the method registered to Android call this.registerUpdateBackColor(); this.registerScanResultFunction(); }, methods:{ //call Android's code scanning method, here you need to pass parameters to Android, so it is empty scan() { $JSbridge.callHandler('scan','',response => { this.code = response;// }) }, //Register The method for receiving the scan code return value registerScanResultFunction() { $JSbridge.registerHandler( "scanResult",(data,responseCallback) => { //Get the Android scan result this.code = data; //Receive successfully and return the value to Android responseCallback("success"); }) }, //Register to modify the background The color method calls registerUpdateBackColor() to Android { $JSbridge.registerHandler("updateBackColor",(data,responseCallback) => { this.backColor = data; console.log(this.backColor) responseCallback("success") }) } }};.def{ width: 100%; height: 1000px;}.black{ background-color: black}.red{ background-color: red;}.blue{ background-color: blue;}

go here You can achieve the effect of starting the picture.

Article Url:

Label group:[software] [android] [js] [js code] [vue] [android js interaction] [android framework] [ios js interaction] [webview

Hot topic

Technology recommend

Technology Popular