An overview of
-
Cordova
Cordova packs your HTML/JS code into a native container that calls all of your system’s hardware and software interfaces (JavaScript apis). We call this a Hybrid App, and thanks to this architecture, we can run the front-end code across platforms and get system features that are close to native apps. It was eventually released to every major App market, including Apple’s App Store.
-
Cordova plug-in
Cordova provides a wide range of software and hardware interfaces for developers through an ecosystem of plug-ins, such as file reading and writing, push notifications, decompression, and contacts. In this way, the corresponding functional plug-ins can be introduced as needed in the development process, and the updating and maintenance of plug-ins can be accelerated to reduce code redundancy. The Cordova plug-in is easily installed and managed by NPM through the CLI.
-
Cross-walk Project
Cross-walk is an open source project developed by Intel to provide a runtime environment for HTML applications. It is based on the latest Chromium core development, providing the latest Web features and consistent compatibility. With the introduction of embedded WebView support for Cordova Android 4.0.0+, you can now easily use Crosswalk WebView for your Cordova applications. By using Crosswalk’s WebView plugin, developers can take advantage of remote debugging, cutting-edge HTML5 features such as WebGL, WebAudio and WebRTC, And significant performance improvements on Android devices including Android 4.0 Ice Cream Sandwich(ICS).
-
Vue.js
Vue.js is a set of progressive frameworks for building user interfaces. Unlike other heavyweight frameworks, Vue is designed with bottom-up incremental development. Vue’s core library focuses only on the view layer and is very easy to learn and integrate with other libraries or existing projects. Vue, on the other hand, is fully capable of driving complex single-page applications developed with single-file components and libraries supported by the Vue ecosystem. Based on Vue framework, the development of single-page Hybrid app will become very efficient.
-
CodePush
CodePush is a cloud service from Microsoft that provides software support and a CDN distribution network for developers to push hot-code-Update directly to users. CodePush provides Cordova developers with plugins that they can quickly implement into their apps. It provides features such as version management, grayscale updates, emergency rollback, incremental updates (Diff), and more. Its CDN is provided by Akamai, the largest CDN service provider in the world, with predictable stability and speed.
Possible future charges
Initialize the development environment
- Nodejs version updateduse
node -v && npm -v
Check the version, if lower than V6.0.0 and V3.0.0, usen
Tool updates:sudo npm install n -g && n stable
- Source management of NPM packagesThe actual source server of NPM is located in the United States, which is slow, so we use alibaba’s NPM source image to replace the default source:
sudo npm install nrm -g && nrm use taobao
, this will set the source address to:registry.npm.taobao.org/
, the server is located in Aliyun, which is fast. - Install Xcode (OS X optional) Download the latest version of Xcode from the Mac App Store and install Command Line Tools for debugging in the iOS emulator.
- Install Android Studio (Mandatory) Go to the Official website of Android Studio to download Android Studio and install SDK 24+. Follow the instructions to complete the installation. Without this step, build and run projects will not succeed.
- Creating a Cordova project Simply follow the official document to create a project: document link
-
You may be stuck in > Configuring > 0/2 projects for several hours when implementing cordova Platform Add Android. The cordova platform add Android command does the following:
- Create the Android project framework and file structure
- Download Gradle for the first time.
- Configure the build.gradle build script
- Download the Maven packages required for the project
- Clear redundant Cordova Lib
- Build the project
Unfortunately, gradle seems to have some bugs when downloading the HTTPS protocol, causing maven packages to fail. This is where some ingenuity is needed:
- Find your Gradle directory, in general
~ /. Gradle/wrapper/dists/gradle - 53 l0mv9mggp9q5m2ip574m21oh 2.14.1 - all / / gradle - 2.14.1 /
Under. - Modify the
src/core/org/gradle/api/artifacts/ArtifactRepositoryContainer.java
The file,MAVEN_CENTRAL_URL
Change the variable torepo1.maven.org/maven2
- Modify the
src/core/org/gradle/api/internal/artifacts/dsl/DefaultRepositoryHandler.java
The file,BINTRAY_JCENTER_URL
Change the variable tojcenter.bintray.com/
- Rebuild the Android project,
cordova platform remove android && cordova platform add android
And you’re done.
-
Run the sample project. Here we try debugging in the emulator and on android:
- IOS:
cordova run ios
The iOS emulator will open automatically after the compilation is complete - Android:
cordova run android
或cordova build android
In the afteryourApp/platforms/android/build/outputs/apk
Find the packaged APK in the directory for real machine installation and debugging. - IOS real machine debugging requires a developer account and a registered developer device, which is not detailed here.
- IOS:
Use the Cordova plugin to introduce cross-walk WebView
In the previous step we successfully got the sample HTML file running in the Cordova environment. However, in the actual development, the Android system version is backward and the native WebView performance is poor and compatibility is poor. Therefore, we need to replace the native Android WebView with cross-walk to run our project. The Cross-walk development community has the Cordova plugin ready for us, just run it: Cordova plugin add cordova-plugin-crosswalk-webview@latest — save cordova plugin add latest to install version 2.2.0+ Otherwise you run into # xwalk-7422. After installing Cordova and building Android, you will find two APK files, one for the ARM platform and one for the x86 platform. The size of the file is about 20Mb larger than the original one. The extra volume is the Crosswalk – WebView Runtime. You can also set this in the config.xml of your project:
<plugin name="cordova-plugin-crosswalk-webview" spec="~ 2.2.0." ">
<variable name="XWALK_VERSION" value="+" />
<variable name="XWALK_LITEVERSION" value="xwalk_core_library_canary:17+" />
<variable name="XWALK_COMMANDLINE" value="--disable-pull-to-refresh-effect" />
<variable name="XWALK_MODE" value="embedded" />
<variable name="XWALK_MULTIPLEAPK" value="true" />
</plugin>
Copy the code
Set the value of XWALK_MULTIPLEAPK to false to create an APK package that integrates both platforms and, of course, blows up to 40Mb+.
Debug projects in the Cross-walk WebView using Chrome
Because cross-walk is based on Chromium, it comes naturally with Chrome’s remote debugging capabilities. Connect your PC to your Android phone and enable USB debug mode. After opening your Cordova project, type Chrome ://inspect in the Chrome browser address bar and select your device to open the remote console. Vue Devtool is also available here.
A small optimization for iOS replaced UIWebView with WKWebView
WKWebView is a new component introduced by Apple in iOS 8. The purpose is to provide a new high-performance WebView solution, and get rid of the old and bulky UIWebView, especially the problem of large memory usage (open a sample project, WKWebView occupies 23M, UIWebView takes 85M). Here we will replace Cordova’s default UIWebView with WKWebView: Cordova plugin add cordova-plugin-wkwebview-engine@latest –save and add to config. XML
<feature name="CDVWKWebViewEngine">
<param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
Copy the code
Use the JavaScript API of Cordova to call the system native interface
You can search for required plug-ins on the plug-in search page. Take Camera plug-in link as an example. Go to the project folder on the command line and enter cordova plugin add cordova-plugin-camera –save.
document.addEventListener("deviceready", func, false);
Copy the code
All plug-ins need to be executed after the func function. Camera methods are defined in the Navigator object, which contains information about the browser and is supported by all browsers. You can simply call navigator.xxx from any js part of the file. However, not all plug-in methods are defined on navigator objects, depending on the specific plug-in documentation. For example, aurora pushes plugins that link to methods defined on the Window object. The use of various methods of the plug-in can refer to the documentation of the corresponding plug-in.
Cordova-plugin-whitelist and CSP security policies
For security reasons, for Cordova 4.0 or higher, Install the cordova-plugin-whitelist plugin and set the
cordova plugin add cordova-plugin-whitelist --save
Copy the code
And edit config.xml:
<! The following is the development environment configuration, does not restrict the source, production packaging needs to set --> <access Origin ="*" />
<allow-intent href="*" />
<allow-navigation href="*" />
Copy the code
Add to index.html:
<! <meta http-equiv= <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: cdvfile: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; font-src * data:; img-src *; script-src *;">
Copy the code
Content-security-policy (CSP) Settings:
- Instructions:
- Instruction value:
Vue. Js fragment packaging mode
In large applications, we may need to split the application into smaller modules that can be downloaded from the server on demand. Vue.js allows you to define a component as a factory function that dynamically resolves the definition of the component. The factory function receives a resolve callback, which is called when it receives the component definition downloaded from the server. Ensure is a commonJS asynchronous load method with empty parentheses. This is equivalent to loading first, but not executing, whereas require is executing. The require.ensure syntax tells Webpack to automatically split compiled code into different chunks. After packing the NPM run build at the command line, there will be an additional JS file and map file in the dist/static/js folder.
routes:[{
path:'/example',component:resolve => require.ensure(['.. /components/example.vue'], () => {
resolve(require('.. /views/example.vue'))})}]Copy the code
If you reference more than two modules in require.ensure functions, such as a route where all components are packaged in the same async, and need to provide the name of the require.ensure third parameter, WebPack will pack them together, such as:
require.ensure([], function(require){
var list = require('./list');
list.show();
var edit = require('./edit');
edit.display();
}, 'all');
Copy the code
List. js and edit.js will be packaged into a single file and named all.js. If you don’t want to pack them together, only two require.ensure references each file. Pay attention to If you want the generated files is that we give the Chunk, need to change the webpack configuration, will build/webpack. Prod. Conf., js 19th row change is as follows:
chunkFilename: utils.assetsPath('js/[name].js')
Copy the code
Added CodePush hot update
In order to realize the single component publishing and hot update functions in the App architecture, CodePush tool developed by Microsoft is introduced.
- Run:
cordova plugin add cordova-plugin-code-push@latest --save
Copy the code
- Install code-push command line and register account (development trial only, official deployment will have a special account) :
Sudo NPM install -g code-push-cli code-push register // you can login to code-push login using Github or Microsoft account // after login, a local session will be generated The file is used to verify your publishing permissionCopy the code
- To create the app:
code-push app add <appName>
Copy the code
This step generates a key that can be copied from the staging key to the next step.
- In the app
config.xml
To configure your deployment key:
<platform name="android">
<preference name="CodePushDeploymentKey" value="YOUR-ANDROID-DEPLOYMENT-KEY" />
</platform>
<platform name="ios">
<preference name="CodePushDeploymentKey" value="YOUR-IOS-DEPLOYMENT-KEY" />
</platform>
Copy the code
- In your
index.html
To allow security policiescodepush.azurewebsites.net
The domain name:
<meta http-equiv="Content-Security-Policy" content="default-src https://codepush.azurewebsites.net ... />
Copy the code
- Add code update logic:
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
const downloadProgress = (progress) => { console.log(`Downloaded ${progress.receivedBytes} of ${progress.totalBytes}`); }
codePush.sync( null, {updateDialog: true, installMode:InstallMode.IMMEDIATE, mandatoryInstallMode: InstallMode.IMMEDIATE}, downloadProgress ); }}; app.initialize();Copy the code
Repackage your app and run it.
- Verify the release code functionality
After modifying any of your code, run:
code-push release-cordova <appName> <platform>
code-push release-cordova MyApp-ios ios
code-push release-cordova MyApp-Android android
Copy the code
- Close the app and re-open it and test if the update is successful
Custom plug-in
You might need to develop some special plug-ins yourself in a real project. This requires some knowledge of native development. Here is an example of developing plug-ins for iOS.
- First, create a plugin directory in any directory, such as rayeye-testPlugin folder in desktop, and then create two new directories SRC and WWW under com.anasit.callnative. SRC stores the plugin code of the corresponding platform. WWW stores the js code of the plug-in, and then create a plugin. XML file, which writes the relevant configuration information of the plug-in. In this example, only the iOS platform is developed, so create the iOS directory under SRC.
-
Create testplugin.js under WWW folder:
var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'); var testPlugin = function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO'.'navigator.testPlugin', arguments); options = options || {}; var getValue = argscheck.getValue; var a = getValue(options.a, 'aaa'); var b = getValue(options.b, 'bbb'); var args = [a, b]; exec(successCallback, errorCallback,"testPlugin"."test",args); }; module.exports = testPlugin; Copy the code
-
For iOS native, create iosplugin. h and iosplugin. m files in SRC/iOS folder:
// IosPlugin.h #import <Cordova/CDV.h> @interface IosPlugin : CDVPlugin - (void)test:(CDVInvokedUrlCommand*)command; @end Copy the code
-
// IosPlugin.m #import "IosPlugin.h" #import <Cordova/CDV.h> @implementation IosPlugin - (void)test:(CDVInvokedUrlCommand *)command{ NSString *s1 = [NSString stringWithFormat:@"% @", [command.arguments objectAtIndex:0]]; NSString *s2 = [NSString stringWithFormat:@"% @", [command.arguments objectAtIndex:1]]; UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:s1 message:s2 delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Sure", nil]; [alertview show]; } @end Copy the code
-
The editor plugin. XML:
<? xml version="1.0" encoding="UTF-8"? > <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="rayeye-TestPlugin" version="0.0.1"> <name> Rayeye-testPlugin </name> <description>Call Native Plugin</description> < License >Apache 2.0</license> <keywords>call native</keywords> <js-module name="testPlugin" src="www/testPlugin.js"> <clobbers target="window.testPlugin"/> </js-module> <platform name="ios"> <config-file target="config.xml" parent="/ *"> <feature name="testPlugin"> <param name="ios-package" value="IosPlugin" /> </feature> </config-file> <header-file src="src/ios/IosPlugin.h" /> <source-file src="src/ios/IosPlugin.m" /> </platform> </plugin> Copy the code
-
Open the cli in the root directory of the project, type Cordova plugin add Rayeye-testPlugin, and press Enter. The plug-in is automatically installed in the plugins directory in the root directory of the project.
-
TestPlugin (SuccessCallback, errorCallback, {a: “111”,b: “222”}); Can pop up a native box.
Android production packaging
- From Android Studio “File”->”Open”, Open/Platforms/Android under your Cordova project.
- Select “Build”->”Generate Signed APK” and click “Next”.
- Select an existing signature or create one. Click on “next”.
- Select the release production version here and click Finish.
IOS production packaging
- That’s if it’s on apple’s Developer site
developer.apple.com/account/
The station generates the required APPID, certificate and profile files, not to mention. - Run the Display Name command to change the application Name.
- Open the project with Xcode, note that the project is.xcworkspace(white), not.xcodeProj (blue).
- In the Resources/Images. Modify the startup in xcassets image and application ICONS, AppIcon is the icon corresponding to the platform, LaunchImage Images is started.
- Choose “Product” – > “Edit Scheme…” In Build Configuration, select Release and click Close.
- Select “Product”->”Archive” from the menu bar, select the project, and select “Export…” , select the first one (Save for iOS App Store Deployment) and click Export. A folder with ipA packages is then generated.
- Open the Application Loader, select Deliver your Application, select the IPA package you generated earlier, and then go to the next step.
- Go to the
Itunesconnect.apple.com/WebObjects/...
Complete the information related to app
Use of aurora push
- Plug-in address
Github.com/jpush/jpush...
- Installation:
cordova plugin add jpush-phonegap-plugin --variable API_KEY=your_jpush_appkey
document.addEventListener("deviceready", onDeviceReady, false); document.addEventListener("jpush.openNotification", onOpenNotification, false); / / click on the notification start or awakening will start the application document. The event addEventListener (" jpush. ReceiveNotification onReceiveNotification, false); / / the application at the front desk receive push will trigger the event document. The addEventListener (" jpush. BackgroundNotification onBackgroundNotification, false); / / receive push back, don't know why, can also do it in the background document. The addEventListener (" jpush. ReceiveMessage onReceiveMessage, false); // The custom message was received