What is a Cordova

  • A mobile application development framework
  • The essence is HTML, CSS, JavaScript wrapped in a native shell
  • PhoneGap, which Adobe acquired in 2011, is the core engine that drives PhoneGap
  • Apache is Apache’s top open source project

Cordova provides a set of device-specific apis that allow mobile applications to access native device functions, such as cameras and microphones, in JavaScript.

Mobile development category

  • Native App
  • Web App
  • Hybrid App

Cordova’s position in the App space

Pros and cons of Cordova

Advantages: cross-platform, easy to transplant, fast development, low cost.

Disadvantages: the execution speed will be relatively slow native, a compilation, debugging everywhere.

Cordova architecture

  • Web App: A place to store application code, represented by your concrete business logic modules.
  • WebView: Provides a complete rendering of user access to the application.
  • Cordova Plugins: Provides an interface to communicate with native components and binds to standard device apis that will be called in JavaScript.

Configure the Environment for Cordova

  1. The installation of the Git
  2. The installation of the Node. Js
  3. Installing Cordova Cli Downloads and installs the global module of Cordova
  4. Install the Java JDK
  5. Install Android Studio Install the Android SDK
npm install -g cordova / cnpm install -g cordova npm install -g cordova --registry=https://registry.npm.taobao.org cnpm Install -g [email protected] // Install the specified version of Cordova --version // View the installed version 10.0.0 of CordovaCopy the code

Build a Cordova project

Cordova create Project name com. company name. Project Name Class Name (Recommended) // Create an empty Cordova project Cordova create cordovademo02 com.itying. Cordova Cordovademo Cordova create MyApp // Create an empty Cordova project Cordova help create // For the complete set of options, runCopy the code

Cordova creation project error:

Uninstall cordova NPM uninstall -g cordova Delete the cordova file NPM \node_modules\cordova NPM install -g cordova --registry=https://registry.npm.taobao.orgCopy the code

Add the platform

CD MyApp Cordova Platform add Android // Add platform Cordova Platform // Run the following command to obtain the complete platform listCopy the code

The directory structure

  • Config. XML configuration page, configure the start page project name and other basic contents
  • Hooks store some custom extension functionality
  • Platforms hosts the added platform runtime
  • Plugins hold imported plug-ins
  • WWW developed HTML5 directory

Actual packaging file platforms/android/app/SRC/main/assets/WWW

Run the project

cordova run android  
Copy the code

Project under the platforms of android directory import android studio to run debug (or run cordova run android)

Note the package name when creating the project: use the package name when packaging the release release, note

For details about how to change the application package name, see www.ionic.wang/article-ind…

1. Change the package name in config. XML

2. Run the Cordova Platform Add Android command again

After modifying the project, run Cordova prepare

Platforms \android\app\ SRC \main\assets\ WWW

Compile the project

cordova build android
Copy the code

Packaging error

Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=F:\software\Android\Sdk (DEPRECATED)
Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
Copy the code

Method 1: Use Android Studio to open the Android directory for input packaging.

Package location: Android \app\build\outputs\ APk \debug

Method 2:

ANDROID_SDK_ROOT = F:\software\Android\ SDK = F:\software\Android\ SDK = F:\software\Android\ SDK

If you don’t know where the Android SDK is, you can do the following:

Open the Android Studio

The environment variables are configured as follows

Gradle will be installed when you first install Android Studio

You can see gradle packages based on + \wrapper\dists. For example: C:\Users\86183.gradle + \wrapper\dists

Add the path to gradle/bin under the system variable path

For example: C: \ Users \ 86183. Gradle \ wrapper \ dists \ gradle – 5.6.4 – all \ ankdp27end7byghfw1q2sw75f \ gradle – 5.6.4 \ bin

Packaging again

Checking Java JDK and Android SDK versions ANDROID_SDK_ROOT=D:\software\Android\Sdk (recommended setting) ANDROID_HOME=D:\software\Android\Sdk (DEPRECATED) Subproject Path: CordovaLib Subproject Path: app FAILURE: Build failed with an exception. * Where: Build file 'D:\MyApp\platforms\android\app\build.gradle' line: 20 * What went wrong: A problem occurred evaluating project ':app'. > Failed to apply plugin [id 'com.android.internal.version-check'] > Minimum supported Gradle version is 5.6.4. Current version is 4.10.3. If using the Gradle wrapper, Editing The distributionUrl in D:\MyApp\gradle\wrapper\gradle-wrapper.properties to gradle-5.6.4-all.zip * try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 3s D:\MyApp\platforms\android\gradlew: Command failed with exit code 1 Error output: FAILURE: Build failed with an exception. * Where: Build file 'D:\MyApp\platforms\android\app\build.gradle' line: 20 * What went wrong: A problem occurred evaluating project ':app'. > Failed to apply plugin [id 'com.android.internal.version-check'] > Minimum supported Gradle version is 5.6.4. Current version is 4.10.3. If using the Gradle wrapper, Editing The distributionUrl in D:\MyApp\gradle\wrapper\gradle-wrapper.properties to gradle-5.6.4-all.zip * try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 3sCopy the code

Manually modified gradle version in the project based on the error

Change gradle-4.10.3-all.zip in project \gradle\wrapper\gradle-wrapper.properties to gradle-5.6.4-all.zip

Package again, error again, and the file is changed back. The gradle-4.10.3-all.zip package was also downloaded.

Do not open the Android directory with Android Studio, Android Studio will probably change the configuration of Cordova.

Application function transformation

Cordova through the document. The addEventListener to listen for an event

The Deviceready event is raised when Cordova is fully loaded. This event is required for every application. It is a signal that the Cordova device API is ready to access.
// Cordova consists of two code libraries: native and JavaScript.
document.addEventListener("deviceready".function() {});
Copy the code

Rewrite the function

Source code: implement the function let. Listening hidden let. Received display

var app = {
  initialize: function() {
    // Deviceready waits for the device API to load
    document.addEventListener(
      "deviceready".this.onDeviceReady.bind(this),
      false
    );
  },

  onDeviceReady: function() {
    this.receivedEvent("deviceready");
  },

  receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector(".listening");
    var receivedElement = parentElement.querySelector(".received");

    listeningElement.setAttribute("style"."display:none;");
    receivedElement.setAttribute("style"."display:block;");

    console.log("Received Event: "+ id); }}; app.initialize();Copy the code

Rewrite code:

// Add deviceready listener and wait for the device API to load

document.addEventListener("deviceready".function() {
  console.log("Device API ready");
  // Make the listening hidden
  // let received display
  setTimeout(() = > {
    var listening = document.querySelector(".listening");
    var received = document.querySelector(".received");

    listening.style.display = "none";
    received.style.display = "block";
  }, 2000);
});
Copy the code

Cordova event

Cordova plug-in and event description

Cordova encapsulates device functions in the form of events or plug-ins

Plug-ins are plug-ins that encapsulate functions provided by devices, such as cameras, contacts, and GPS. They are provided in the form of user-defined JS root objects or overwriting standard objects. Plug-ins need to be installed separately to be used.

Cordova Event Overview

The name of the event instructions
deviceready This event is triggered when Cordova is loaded
pause This event is emitted when the application is put in the background
resume This event is emitted when the application returns from the background
backbutton This event is emitted when the back button is pressed
. .

Use of Cordova events

All events are called in the same way, with js event listener (addEventListener)

document.addEventListener("deviceready", onDeviceReady,false);

function onDeviceReady() {
  document.addEventListener("pause", onPause, false);
  document.addEventListener("resume", onResume, false);
  document.addEventListener("menubutton", onMenuKeyDown, false);
  // Add similar listeners to other events
}
Copy the code

Process for starting Cordova applications

HTML page loading process

  1. Native code startup
  2. splashscreen
  3. load html
  4. Sequential execution of JavaScript => Cordova.js is also executed
  5. $(document).ready() is executed, events in Cordova may not be available.
  6. Register the Deviceready event

Code examples:

/* * Cordova encapsulates device apis in plugins and events. * Cordova monitors events like */

/* * 1, deviceready API is ready to execute some low-level events or methods based on the device API, after the deviceready event is called, execute * 2, pause when the application is suspended into the background. Resume is called when the application returns to the front. Backbutton is called when the back key is clicked

/* * When deviceready device API is ready, call * parameter 1: event name * parameter 2: callback function * parameter 3: whether to execute in capture phase, default false (bubble phase), directly default */

// Wait is the loading of device code for the underlying Cordova
document.addEventListener("deviceready".function() {
  log("The device API is ready to call other methods or listen for events.");

  // Add application suspension listening
  document.addEventListener("pause".function() {
    log("The application is suspended.");
  });

  document.addEventListener("resume".function() {
    log("The app is back.");
  });

  document.addEventListener("backbutton".function() {
    log("The back key has been clicked.");
  });
});

// Outputs the log content to the screen body
function log(msg) {
  var p = document.createElement("p");
  p.style.fontSize = "14px";
  p.innerHTML = msg;
  // Output to body
  document.body.appendChild(p);
}
Copy the code

The plug-in

Plug-in uninstall

cordova plugin rm cordova-plugin-network-information
Copy the code

Use the Cordova plug-in

equipment

Installing a plug-in

cordova plugin add cordova-plugin-device
Copy the code

network

Installing a plug-in

cordova plugin add cordova-plugin-network-information
Copy the code

The equipment location

Installing a plug-in

cordova plugin add cordova-plugin-geolocation
Copy the code

file

Installing a plug-in

Cordova plugin add cordova-plugin-file-transfer // File transfer cordova plugin add cordova-plugin-file // File transfer cordova pluginCopy the code

Battery status

1. Install the battery plug-in

cordova plugin add cordova-plugin-battery-status
Copy the code

2. Add event listener

Event listeners must be called after the Deviceready call is complete, and listeners must be added through Window

document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { window.addEventListener("batterystatus", onBatteryStatus, false); } function onBatteryStatus(status) {console.log(" Battery status: Level: "+ status. Level +" isPlugged: "+ status.isPlugged); }Copy the code

The event returns a status object with two attributes: level: the percentage value of the current battery, which ranges from 0 to 100. Number Value type isPlugged: Indicates whether the phone is currently charging. Boolean type

Three events:

The name of the event Events that
batterystatus Triggered when the battery changes by 1%, or when the charging state changes
batterylow This event is triggered when the percentage of battery power reaches a low value. This value may vary on different devices.
batterycritical This event is triggered when the percentage of battery power reaches a critical value. This value may vary on different devices.

Code examples:

// To use the cordova plug-in, install it first. Cordova plugin add cordova-plugin-battery-status // 2. This plug-in can be used to monitor device battery changes. It provides three events globally. (1) batterystatus indicates that the batterystatus has changed (at least 1% of the charge level has changed) or batterycritical is triggered (3) Batterylow indicates that the battery level is low, triggering // Note: Plug-in event listeners and plug-in method calls must be called after Deviceready is ready. All events return a status object, This object has two properties // (1) status.level indicates the percentage of the device's battery capacity (0-100) Number // (2) status.isPlugged indicates whether the device is charging. Boolean True Indicates that the device is charging, False is not charging / / wait for cordova equipment API to load the document. The addEventListener (" deviceready ", function () {/ / cordova equipment API loading is completed, You can addEventListener window.addEventListener("batterystatus", onBatterystatus); window.addEventListener("batterycritical", onBatterycritical); window.addEventListener("batterylow", onBatterylow); }); Function onBatterystatus(status) {log(" current battery: "+ status.level +" whether it isPlugged in: "+ status.isPlugged); } function onBatterycritical(status) {log(" The current battery has reached the critical value, the current battery: "+ status.level +" charging: "+ status.isPlugged); } function onBatterylow(status) {log(" the current battery is low, the current battery: "+ status.level +" is charging: "+ status.isPlugged); Function log(MSG) {var p = document.createElement("p"); p.style.fontSize = "14px"; p.innerHTML = msg; / / output to the body of the document. The body. The appendChild (p); }Copy the code

The camera

The plugin defines a global navigator.camera object that provides apis for taking photos or working with gallery files

This object is only available after the Deviceready event is triggered.

1. Install the camera plug-in

cordova plugin add cordova-plugin-camera
Copy the code

2. Photo taking function

Call navigator.camera. Cleanup (onSuccess, onFail) after ios takes a photo; Clear cache / / photo camera function takePicure () {/ / call the plugin API provides the navigator. Camera global object navigator. Camera. GetPicture (onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.DATA_URL }); function onSuccess(imageData) { var img = document.querySelector("img"); img.src = "data:image/jpeg; base64," + imageData; } function onFail(message) { console.log( "failed because " + message ); }}Copy the code

3. Read pictures from album

/ / select photos function function selectPicure () {the navigator. Camera. GetPicture (onSuccess, onFail, {quality: 50, destinationType: Camera.DestinationType.NATIVE_URI, sourceType: Camera.PictureSourceType.PHOTOLIBRARY }); function onSuccess(imageURL) { var img = document.querySelector("img"); img.src = imageURL; } function onFail(message) { console.log('Failed because: ' + message); }}Copy the code
Parameter names Configuration values
quality Image quality in the 0-100 range. The default value is 50.
destinationType DATA_URL or 0 returns a Base64 encoded string
FILE_URI or 1 returns the image file URI
NATIVE_URI or 2 returns the image’s local URI
sourceType PHOTOLIBRARY or 0 open the PHOTOLIBRARY
CAMERA or 1 turn on the CAMERA
SAVEDPHOTOALBUM or 2 open save album
allowEdit Allow image editing
encodingType JPEG0Returns a JPEG – encoded image
PNG1Returns a Png-encoded image
targetWidth Zoom width of pixels in an image
targetHeight The height of pixels in an image in proportion
cameraDirection FRONT0Front facing camera
BACK1Rear camera

Code examples:

// Cordova provides apis for calling camera devices. Install the corresponding plug-in. Cordova plugin add cordova-plugin-camera // 2. This plugin provides a global object navigator. Camera provides a set of apis that help us take photos or read images from albums // Note: // In the navigator. Camera object, there is a method called getPicture(success, error, options ); // getPicture can be used to take pictures or read pictures from albums // options: // (1) destinationType: // Default: FILE_URI Returns file path // (3) sourceType: set CAMERA to use, or read from album // Default: CAMERA to use CAMERA /* Requirements: 1. Var btn1 = document.getelementById ("btn1"); var btn1 = document.getelementById ("btn1"); Var btn2 = document.getelementById ("btn2"); Var btn3 = document.getelementById ("btn3"); Var img = document.querySelector("img"); / / get picture dom document object. The addEventListener (" deviceready ", function () {/ / wait for equipment API loading / / the console. The log (the navigator. Camera); btn1.addEventListener("click", takePic); btn2.addEventListener("click", takePicBase64); btn3.addEventListener("click", getPic); }); Function takePic () {/ / call getPicture method, can take photos / / the navigator. Camera. GetPicture (success, error, options); The navigator. Camera. GetPicture (success, error, {quality: 50, / / the quality of the picture, the default value is 50 range 0-100 destinationType: Camera. DestinationType. FILE_URI, / / display, return image url sourceType: Camera. PictureSourceType. Camera, the default Camera / / photograph by Camera targetWidth: 100, / / keep original proportion, compressing display targetHeight: 100}); Function success(fileurl) {console.log(fileurl); // By default, success returns the file path img. SRC = fileurl; } function error() {console.log(" failed to take photo "); }} function takePicBase64() {getPicture(success, error, options); The navigator. Camera. GetPicture (success, error, {quality: 50, / / said the quality of the picture destinationType: Camera. DestinationType. DATA_URL, / / base64 encoded string sourceType: Camera. PictureSourceType. The default Camera Camera / / photograph by Camera}); function success(base64str) { console.log(base64str); Console. log(" Photo taken successfully "); // Img. SRC = "data:image/jpeg; base64," + base64str; } function error() {console.log(" failed to take photo "); {}} function getPic () the navigator. Camera. GetPicture (success, error, {quality: 50, / / said the quality of the picture destinationType: Camera. DestinationType. FILE_URI, / / returns the image path sourceType: Camera. PictureSourceType. PHOTOLIBRARY/source/configuration picture album}); function success(fileurl) { img.src = fileurl; Console. log(" Read image from album successfully "); } function error() {console.log(" failed to read from album "); }}Copy the code

vibration

1, install vibration plug-in

cordova plugin add cordova-plugin-vibration
Copy the code

2, vibration use

navigator.vibrate(time);
navigator.vibrate([time]);
Copy the code
// Stop the vibration
navigator.vibrate(0);
navigator.vibrate([]);
navigator.vibrate([0]);
Copy the code

Code examples:

// 1. Install the cordova plugin add cordova-plugin-vibration
// 2. Use the vibration API
// There is a global method called navigator.vibrate to complete the vibration
// Note: the vibration API needs to be called after Deviceready

// Navigator.vibrate calls both ways
// 1. navigator.vibrate( 3000 ); Vibration once, vibration 3 seconds, the longest can only 5s
// 2. navigator.vibrate( [ 3000, 1000, 3000, 1000 ] ); Vibrate for 3 seconds, pause for 1 second, vibrate for 3 seconds, and stop for 1 second

// To stop the vibration, pass 0 to method
// navigator.vibrate( 0 );
// navigator.vibrate( [] );

var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var stop = document.getElementById("stop");

document.addEventListener("deviceready".function() {
  // The device API is ready to call the device API
  btn1.addEventListener("click".function() {
    navigator.vibrate(5000);
  });

  btn2.addEventListener("click".function() {
    navigator.vibrate([3000.1000.3000.1000]);
  });

  stop.addEventListener("click".function() {
    navigator.vibrate(0);
  });
});
Copy the code

multimedia

1. Install the plug-in

cordova plugin add cordova-plugin-media
Copy the code

2, multimedia play, pause, stop

Function playAudio() {var SRC = "/android_asset/ WWW /video/bg.mp3"; If (myMedia === null) {myMedia = new Media(SRC, onSuccess, onError); function onSuccess() { console.log("playAudio Success"); } function onError(error) { console.log("playAudio Error: " + error.code); }} console.log(" Play music "); Mymedia.play (); } function pauseAudio() {if (myMedia) {console.log(" pause music "); myMedia.pause(); Function stopAudio() {if (myMedia) {mymedia.stop (); } console.log(" Stop audio "); myMedia = null; Var volumeValue = 0.5; Function volumeUp() {if (myMedia && volumeValue < 1) {myMedia. SetVolume (volumeValue += 0.1); } console.log(" current volume :" + volumeValue); } function volumeDown() {if(myMedia && volumeValue > 0) {myMedia. SetVolume (volumeValue -= 0.1); } console.log(" current volume :" + volumeValue); }Copy the code

Table of methods provided by the plug-in:

methods instructions
getCurrentPosition Returns the current position of the audio
getDuration Returns the duration of an audio
play Used to start or resume audio
pause Used to pause audio
release Publish audio resources for the underlying operating system
seekTo Used to change the position of audio
setVolume Used to set the volume of audio
startRecord Start recording the audio file
stopRecord Stop recording audio files
stop Stop playing the audio file

Config.xml configuration

Change the name

<widget .>
  <name>HelloCordova</name>
</widget>
Copy the code

Change the description

<widget .>
  <description>A sample Apache Cordova application</description>
</widget>
Copy the code

Change the icon

<widget .>
  <icon src="res/icon.png" />
</widget>
Copy the code

cordova vue

Package the VUE project as an app:

1, NPM run build (note: image directory path)

2. Copy the static resources packaged with VUE into the Cordova project

3. Run Prepare for Cordova

Note:

Vue init webpack-simple Project name

Modified: publicPath in webpack.config.js

Change publicPath: ‘/dist’ to publicPath: ‘dist ‘

Change the path to dist in index to remove the first/(important)

Vue Init Webpack project name

Change assetsPublicPath: ‘/’ to assetsPublicPath: ‘./’

Call native API in Vue:

Use vue-Cordova (not recommended)

NPM install –save VUe-cordova

2. Introduce the plugin in main.js and use the plugin

import VueCordova from 'vue-cordova'
Vue.use(VueCordova)
Copy the code

3. Call the plug-in note that it needs to be introduced in the corresponding component

var Vue = require('vue');
Vue.cordova.camera.getPicture((imgeURL) = > {
    window.alert('Photo URL:' + imageURL)
},(message) = >{
    window.alert('FAILED:' + message)
},{
    quality:50.destinationType:Vue.cordova.camera.DestinationType.FILE_URL
})
Copy the code

4. Note that cordova needs to be introduced in vue project index.html

<script src="cordova.js"></script>
Copy the code

Use index.html to import cordova. Js and define global variables to use cordova directly in vue components (recommended)

1, introduce cordova.js to vue index.html (note the order cordova.js is placed above build.js)

2. You can use the API for cordova directly in the component.


The relevant data

  • Cordova Mixed App Introduction (1)
  • The relevant code
  • Cordova Chinese website
  • Android Studio view the SDK path configuration
  • Build a Development environment for Cordova
  • Cordova Device plugin – Get device information
  • Cordova is back to version 7.0.0
  • Cordova generated slow problem, stuck in Gradle: Download https://services.gradle.org/
  • vue-cordova