Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.
Cordova + vue packages Android [Android] apk and Apk version automatic upgrade and installation [get download progress in real time]
Prepare
Environment: node.js, Android sbk, jdk, npm
node.js official website: https://nodejs.org/zh-cn/ Download and install node.js, install After completion, use "node -v" in the command line (cmd) to verify whether the installation is successful.
npm: The new version of node has integrated npm. Enter "npm -v" on the command line to test whether the installation is successful.
1. Cordova + vue package Android apk
1. Install the Cordova environment
use:
npm install -g cordova
To install cordova globally
After the installation is complete, use: cordova -v to check whether the installation is successful
2. Create a new Cordova project (it is recommended to place it in the English directory)
Execute line command
cordova create myApp
myapp - cordova directory name
cd myApp to enter the directory
Use command
cordova platform add android
to generate the cordova library for the Android platform, then an android folder will be generated in the platforms folder.
In the generated cordova file:
config.xml - contains application-related information, plug-ins used and target platforms
platforms – Contains the corresponding Cordova libraries for application running platforms such as Android and iOS
plugins – Contains the Cordova libraries required by the application, allowing the application to access matters related to camera and battery status, for example.
www – Contains application source code, such as HTML, JavaScript and CSS files
hooks – Contains scripts required to compile the system for personalized applications
At this point, the cordova project has been built.
3.Package the Vue project into the cordova project
(If you don’t have a vue project yet, please read this blog: https://www.cnblogs.com/qirui/p/8421372.html)
You need to first change the publicPath attribute in vue.config.js to: "/" (if there is no vue.config.js file, Baidu can create one in the root directory using a template)
Then use the packaging command
npm run build
Then copy all the files in the packaging folder (packaged in the dist folder by default) to the www directory under the cordova project (delete all the files in the original www directory)
4. Debugging the packaged apk software
Before packaging, check whether the packaging-related environment is installed correctly and execute the command in the cordova project folder.
cordova requirements
to view the installation status in the current environment. The following display indicates that the environment is correctly installed. (Just make sure the installation is correct, there is no need to check every time)
Joint debugging of Android software (requires connection to a real machine or emulator)
cordova run android
5. Package into Android apk
Excuting an order
cordova build android -release
It can be packaged as a release version apk
The red box marks the path where the apk is located
6.APK signature
All APKs must be digitally signed before they can be installed on the device. Signing requires a corresponding certificate (keystore). In most cases, APKs use self-signed certificates, which means they generate the certificate themselves and then sign the application.
The digital signature certificate is a necessary file for packaging the APK, so the digital signature certificate must be generated first.
Enter at the command line:
keytool -genkey -v -keystore D:\mytest.keystore -alias mytest -keyalg RSA -validity 20000
-keystore D:/mytest.keystore represents the generated certificate and its storage path. If you write the file name directly, it will be generated in the user's current directory by default;
-alias mytest represents the certificate The alias is mytest. If you do not write this item, the certificate name defaults to mykey;
-keyalg RSA indicates the RSA algorithm used;
-validity 20000 indicates the certificate The validity period is 20,000 days.
After filling in the relevant information, enter y at the end [No]
The generated certificate file
Then put the certificate and apk in the same directory
Command line input:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore myapp.keystore app-release-unsigned.apk myapp
Perform signature operation
At this time, the apk is already a signed apk.
7. Frequently Asked Questions
probably means that the packaged directory has Chinese characters. You can add android.overridePathCheck=true to the configuration file to ignore this error.
…\myapp\platforms\android Find the gradle.properties file in this directory.
Just add android.overridePathCheck=true
2. Automatic upgrade and installation of Apk version (obtain download progress in real time)
1.Install the Android plug-in
Enter the cordova project root directory
Enter the command line
cordova plugin add cordova-plugin-app-version //获取版本号
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-opener2
cordova plugin add cordova-plugin-file-transfer
cordova plugin add cordova-plugin-whitelist
2. Add cordova.js
Add it to index.html of the vue project
<script src="cordova.js"></script>
3. Create version update js
Create upgrade.js
import apis from '@/request'
import {
Dialog } from 'vant';
Dialog.setDefaultOptions({
confirmButtonColor:"#006BE0",
closeOnPopstate:false
})
//检测新版本升级
export function upgradeForAndroid(releasePath, packageName) {
//从window中获取Cordova对象
var cordova = window.cordova
//apk所在的服务器路径(下载路径)
var url = process.env.VUE_APP_APK_URL + process.env.VUE_APP_APK_NAME + ".apk";
var targetPath = cordova.file.externalCacheDirectory + "Download/Pass/" + "test.apk"; //要下载的目标路径及文件名(本地存储路径)
var trustHosts = true;
var options = {
};
console.log("url:" + url);
console.log("targetPah:" + targetPath);
console.log("trustHost:" + trustHosts);
downLoadApp();
function downLoadApp() {
// 初始化FileTransfer对象
// eslint-disable-next-line no-undef
var fileTransfer = new FileTransfer();
fileTransfer.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
var downloadProgress = (progressEvent.loaded / progressEvent.total) * 100;
var result = "已下载:" + Math.floor(downloadProgress) + "%";
console.log(result,"已经下载")
if(Math.floor(downloadProgress) == 100){
Dialog.alert({
title: result,
message:"下载完成后会自动弹出安装",
showConfirmButton:false,
showCancelButton:true
}).then(
).catch(() => {
// on cancel
navigator.app.exitApp();
})
}else{
Dialog.alert({
title: result,
message:"下载完成后会自动弹出安装",
showConfirmButton:false,
showCancelButton:false
})
}
}
};
// 调用download方法
fileTransfer.download(
url, //uri网络下载路径
targetPath, //url本地存储路径
function (entry) {
console.log("download complete: " + entry.toURL());
cordova.plugins.fileOpener2.open(
targetPath,
'application/vnd.android.package-archive',
{
error: function (e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
Dialog.alert({
title: "打开下载文件失败",
message:"请退出后重新进入应用",
}).then(res => {
navigator.app.exitApp();
})
},
success: function () {
console.log('open successfully');
}
})
},
function (error) {
// AlertModule.show({ title: "下载失败" })
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
}
/*
* 检测升级方法
*/
export function checkUpgrade(locationVersion) {
/**
* 从服务器获取应用的版本信息,和本地应用版本对比
*/
apis.updateVersion.getAppVersion().then(response => {
if(response != null){
var serverVersion = response.data.appVersion;
//获取本地App版本;
console.log("本地版本:" + locationVersion);
console.log("服务器版本:" + serverVersion);
var locationVersionNum = parseInt(locationVersion.replace(/\./g,""))
var serverVersionNum = parseInt(serverVersion.replace(/\./g,""))
if(locationVersionNum < serverVersionNum){
Dialog.confirm({
title: '发现版本: ' + serverVersion + ',请进行升级',
message: '建议您在WIFI环境下升级',
}).then(() => {
// on confirm
upgradeForAndroid()
}).catch(() => {
// on cancel
navigator.app.exitApp();
});
}
}
})
// 监听网络状况,无网络时
document.addEventListener('offline', function () {
console.log("网络异常,不能连接到服务器!");
Dialog.alert({
title:"网络异常,不能连接到服务器!",
message:"请在连接网络的情况下升级应用"
}).then(() => {
navigator.app.exitApp();
})
}, false);
}
apis: encapsulated request instance
Dialog: pop-up component The reference here is the v-vant pop-up plug-in
4. Call version update
Call the method in this js when entering the app
What the server needs to do is to store a current version number for the app to send a request to compare with the local version number. , and upload the new version of the apk to a location on the server for the app to download.
5. Packing precautions
Be careful to upgrade the version number when packaging
Enter the root directory of the cordova project and find config.xml
Change the version number here
6. Other matters needing attention
Requests for Android version 9.0 and above must use https requests, otherwise the request will be forcibly ended and the status code will return 0
If you need to use http request, add android:usesCleartextTraffic="true
in (.../platforms/android/app/src/main/AndroidManifest.xml) to solve the problem question.