当前位置:网站首页>Advanced cross platform application development (III): online resource upgrade / hot update with uni app

Advanced cross platform application development (III): online resource upgrade / hot update with uni app

2022-07-01 05:40:00 No Silver Bullet


One 、 Preface

Use uni-app Develop cross terminal applications , The code can be compiled into iOSAndroid、 Wechat applets and other platforms , When upgrading, it is also necessary to consider multi platform synchronous upgrading . among ,uni-app The upgrade mode of publishing as an applet is relatively simple , Just submit the developed code to the applet background , Users will be upgraded automatically after approval .

HBuilderX 1.6.5 rise ,uni-app Support generation App Resource upgrade package wgt.

Two 、wgt Resource upgrade package upgrade

2.1 Change the version number

First , to update manifest.json Version number in .
Like before 1.0.0, Then the new version should be 1.0.1 or 1.1.0 such .
 Insert picture description here

2.2 issue

then , stay HBuilderX Generate upgrade package in (wgt).

 menu -> issue -> Native App- Make mobile App Resource upgrade package 

 Insert picture description here
After generation, the console will tell you the output location of the upgrade package .
 Insert picture description here

2.3 Install the resource upgrade package

The application upgrade needs the cooperation between the server and the client , The following is an example of the operation in the local test process :

Depositing resources
take %appid%.wgt The file is stored in the server's static Under the table of contents , namely http://www.example.com/static/UNI832D722.wgt.

Server interface
Agree to detect the upgraded interface , The address is :http://www.example.com/update/

Pass in the parameter

  • name String ‘’ Application name read by client , Defining this parameter can facilitate multiple application reuse interfaces .
  • version String ‘’ Version number information read by the client

Returns the parameter

  • update Boolean false Is there an update
  • wgtUrl String wgt Download address of the package , be used for wgt Way update .
  • pkgUrl String apk/ipa Package download address or AppStore Address , How to upgrade a package .

2.3.1 Code example

The following is a simple example of server-side decision , Just for your reference , In actual development, it is handled according to its own business needs .

var express = require('express');  
var router = express.Router();  
var db = require('./db');  

// TODO  Query the configuration file or database information to see if there is an update   
function checkUpdate(params, callback) {
      
    db.query(' a section SQL', function(error, result) {
      
        //  Here is a simple judgment , Inequality is renewal .  
        var currentVersions = params.appVersion.split('.');  
        var resultVersions = result.appVersion.split('.');  

        if (currentVersions[0] < resultVersions[0]) {
      
            //  There is a large version update   
            callback({
      
                update: true,  
                wgtUrl: '',  
                pkgUrl: result.pkgUrl  
            })  
        } else {
      
            //  Other cases are considered as minor version updates   
            callback({
      
                update: true,  
                wgtUrl: result.wgtUrl,  
                pkgUrl: ''  
            })  
        }  
    });  
}  

router.get('/update/', function(req, res) {
      
    var appName = req.query.name;  
    var appVersion = req.query.version;  
    checkUpdate({
      
        appName: appName,  
        appVersion: appVersion  
    }, function(error, result) {
      
        if (error) {
      
            throw error;  
        }  
        res.json(result);  
    });  
});

matters needing attention

  • The specific decision logic of the server , Please handle it flexibly according to your own business logic .
  • Try not to include special symbols in the path in the application .

Client detection upgrade
stay App.vue Of onLaunch Upgrade detected in , The code is as follows :

// #ifdef APP-PLUS 
plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
      
    uni.request({
      
        url: 'http://www.example.com/update/',  
        data: {
      
            version: widgetInfo.version,  
            name: widgetInfo.name  
        },  
        success: (result) => {
      
            var data = result.data;  
            if (data.update && data.wgtUrl) {
      
                uni.downloadFile({
      
                    url: data.wgtUrl,  
                    success: (downloadResult) => {
      
                        if (downloadResult.statusCode === 200) {
      
                            plus.runtime.install(downloadResult.tempFilePath, {
      
                                force: false  
                            }, function() {
      
                                console.log('install success...');  
                                plus.runtime.restart();  
                            }, function(e) {
      
                                console.error('install fail...');  
                            });  
                        }  
                    }  
                });  
            }  
        }  
    });  
});  
// #endif

Resource upgrade packages are not supported as follows :

  • SDK Partial adjustment , For example, new Maps Module etc. , Cannot be upgraded in this way , Must be upgraded in a package .
  • Adding and modifying native plug-ins , The same cannot be used .
  • For the old non custom component compilation mode , This model has been eliminated . But just in case you need to explain , Old non custom component compilation mode , If the previous project did not nvue file , But new in the update nvue file , This method cannot be used . Because if there is no custom component compilation mode nvue Files are not packaged weex The engine went in , Native engine cannot be added dynamically . The custom component mode contains weex engine , Whether or not there is nvue file .

matters needing attention ️

  • Conditional compilation , Only in App The platform performs this upgrade logic .
  • appid And version information , stay HBuilderX During real machine operation and development , Are all HBuilder Information about this app , Therefore, you need to pack a custom base or a formal package to test the upgrade function .
  • plus.runtime.version perhaps uni.getSystemInfo() What I read is apk/ipa Version number of the package , Instead of manifest.json Version information in resources , So here we use plus.runtime.getProperty() To get relevant information .
  • ️ install wgt After resource package success , Must be implemented plus.runtime.restart(), Otherwise, the new content will not take effect .
  • If App Native engine of does not upgrade , Upgrade only wgt Pay attention to the test when packaging wgt Resource and native base compatibility ️. The platform will remind the mismatched version by default , If the self-test is OK , Can be in manifestt.json Configure ignore prompt in .
  • ️ The application market is to prevent developers from getting approval from the market , Provide users with illegal content , Most of them reject hot renewal .

But in fact, hot update is very common , Whether it's native development or cross platform development .

Apple Once banned jspatch, There are no other hot plans to combat , Include cordovar、react native、DCloud. kill jspatch Because jspatch There are serious security vulnerabilities , Can be used by hackers , Causing third-party hackers to tamper with other App The data of .

Using hot update requires attention ️:

  • ‍*️ Don't pop up the hot update prompt during the launch audit ;
  • ️ Hot update content use https download , Avoid being hijacked by tripartite network ;
  • Don't update illegal content 、 Don't destroy the benefits of application market through hot update , such as iOS The virtual payment of Apple Cents .

3、 ... and 、 Package upgrade

Interface agreement
The following data interface conventions are only examples , Developers can customize interface parameters .

Request address :https://www.example.com/update

Request method :GET

Request data :

{
      
    "appid": plus.runtime.appid,  
    "version": plus.runtime.version  
}  

The response data :

{
      
    "status":1,// Upgrade flag ,1: Need to upgrade ;0: No need to upgrade   ` Insert a code chip here `
    "note": " Repair bug1;\n Repair bug2;",//release notes  
    "url": "http://www.example.com/uniapp.apk" // Update package download address   
} 

3.1 Client implementation

App Startup time , Report the current version number to the server , The server determines whether to prompt for upgrade .

stay App.vue Of onLaunch in , Initiate an upgrade detection request , as follows :

onLaunch: function () {
      
    //#ifdef APP-PLUS 
    var server = "https://www.example.com/update"; // Check update address   
    var req = {
     // Upgrade detection data   
        "appid": plus.runtime.appid,  
        "version": plus.runtime.version  
    };  
    uni.request({
      
        url: server,  
        data: req,  
        success: (res) =&gt; {
      
            if (res.statusCode == 200 &amp;&amp; res.data.status === 1) {
      
                uni.showModal({
     // Remind users to update   
                    title: " Update hints ",  
                    content: res.data.note,  
                    success: (res) =&gt; {
      
                        if (res.confirm) {
      
                            plus.runtime.openURL(res.data.url);  
                        }  
                    }  
                })  
            }  
        }  
    })  
    //#endif 
}  

Be careful ️:App The upgrade detection code of must use Conditional compilation , Otherwise, the wechat environment does not exist plus relevant API, Will be an error .

3.2 Data table implementation

A data sheet needs to be maintained , For maintenance APP Version information , The main field information is as follows :

Field name data type Data description
AppIDvarcharmobile AppID
versionvarchar Application market version number
notesvarchar Version update instructions
urlvarchar App Market Download URL. Be careful :️ According to Google 、App Store Apply market audit specifications , Application upgrades can only be made by submitting application market updates , Cannot download apkIPA Installation mode update application .

3.3 Server implementation

According to the version number received by the client , Compare the latest version number of the server , Decide whether to upgrade , If you need to upgrade, return the upgrade information (rlease notes Update package address etc. )

Developers can develop languages according to the server , Realize the upgrade detection logic by yourself , Here is a php Sample code :

header("Content-type:text/json");  
$appid = $_GET["appid"];  
$version = $_GET["version"]; // Client version number   
$rsp = array("status" =&gt; 0); // Default return value , No need to upgrade   
if (isset($appid) &amp;&amp; isset($version)) {
      
    if ($appid === "__UNI__123456") {
     // check appid  
        if ($version !== "1.0.1") {
     // Here's the sample code , In real business , Latest version number and relase notes Can be stored in a database or file   
            $rsp["status"] = 1;  
            $rsp["note"] = " Repair bug1;\n Repair bug2;"; //release notes  
            $rsp["url"] = "http://www.example.com/uniapp.apk"; // Application upgrade package download address   
        }  
    }  
}   
echo json_encode($rsp);  
exit;  

matters needing attention ️:

  • plus.runtime.appid,plus.runtime.version, plus.runtime.openURL() Only in the real machine environment .
  • Version detection needs to be packaged app, The real machine running base cannot be tested . Because the real machine runs plus.runtime.version It's a fixed value .
  • According to the Google application market audit specification , Application upgrades can only be made by submitting application market updates , Cannot download apk Installation mode update application .apk The installation failure may be due to the lack of android.permission.INSTALL_PACKAGESandroid.permission.REQUEST_INSTALL_PACKAGES Authority results in , Be careful : Adding the above two permissions cannot be approved by Google .

Four 、Uni-app Version upgrade Center

uni-app Provides a complete version maintenance framework , Contains the upgrade Center uni-upgrade-center - Admin、 Foreground detection update uni-upgrade-center-app.

4.1 Upgrade Center uni-upgrade-center - Admin

uni-app It provides a version maintenance background application upgrade Center uni-upgrade-center - Admin, The upgrade center is a uni-admin plug-in unit , be responsible for App Version update business . Including background management interface 、 Update check logic ,App Just call the pop-up prompt .
 Insert picture description here
Fill in the release information in the upload installation package interface , The package address can choose to manually upload a file to the cloud storage , The address will be automatically filled in this item .

You can also fill in an address manually ( for example :https://appgallery.huawei.com/app/C10764638), You can no longer upload files .

️ If it's an apple release , Package address is applied in AppStore Link to .
 Insert picture description here
The upgrade center has the following function points :

  • Cloud storage installation package CDN Speed up , Make the installation package download faster 、 A more stable
  • Application management , Yes App Information recording and application version management .
  • version management , You can release a new version , It can also be convenient and intuitive for the current App Historical version and online release version 、 Edit and delete operations .
  • Version release information management , Including updates title , Content , Version number , Silent update , Force update , Flexible online distribution settings and modifications .
  • Native App Installation package , Release Apk to update , be used for App Full package update for , You can set whether to force update .
  • wgt Resource Pack , Release wgt to update , be used for App Hot update of , You can set whether to force update , Silent update .
  • App Management list and App Version record list search .
  • Just import the plug-in , Initialize the database to have the above functions .
  • You can also modify the logical custom database fields by yourself , And customizable UI style .

4.2 Foreground detection update uni-upgrade-center-app

uni-upgrade-center-app Be responsible for the front desk to check the update .

The project structure is shown in the figure below :
 Insert picture description here
The detection update view is shown in the following figure :
 Insert picture description here  Insert picture description here
The plug-in provides the following functions :

  • Unified management App And App stay AndroidiOS On the platform App Install the package and wgt Release and upgrade of resource packs .
  • be based on uni-upgrade-center One click Check for updates , Unified package and wgt Resource pack update .
  • Complete the verification according to the parameters transferred , Determine which method to use for this update .
  • One click upgrade . Integrated bullet frame 、 download 、 install 、 Whether to force restart and other logic .
  • After downloading, if you cancel the upgrade, the installation package will be automatically cached , Enter next time to judge whether the installation conditions are met , If the judgment fails, it will be cleared automatically .
  • beautiful , practical , Customizable extension .

Be careful :️ Obtained when running on the mobile phone base Version number and appid yes hbuilder and hbuilder Version of It needs to be set manually in the file .

4.3 working principle

Upgrade Center uni-upgrade-center - Admin Maintain version information , And maintain the version information in the database .
Foreground detection update plug-in uni-upgrade-center-app It is responsible for calling cloud functions to read the version information maintained by the database, and one click Check for updates .

4.4 doubt

  • Foreground detection update plug-in uni-upgrade-center-app Use cloud functions to realize version detection , When the application is deployed to the intranet , How to achieve ?

5、 ... and 、 Expanding reading

原网站

版权声明
本文为[No Silver Bullet]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160213201624.html