ionic3 APP版本更新

ionic3 APP版本更新_第1张图片
Ionic 等版本信息

注意:安装平台android 6.3.0的小伙伴,安装插件时,一定要选择下面的版本安装,否则出错。
platforms\android\AndroidManifest.xml
android:targetSdkVersion版本

// 1 安装插件
 // 权限 
$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/[email protected]
// 文件管理 
$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/[email protected]
// 文件上传 
$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/[email protected]

$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/[email protected]
// 版本检测 
$ ionic cordova plugin add [email protected] 
$ npm install --save @ionic-native/[email protected] 
// 浏览器 
$ ionic cordova plugin add cordova-plugin-inappbrowser 
$ npm install --save @ionic-native/in-app-browser 



//添加插件 
//app.module.ts 
import { AndroidPermissions } from '@ionic-native/android-permissions'; 
import { File } from "@ionic-native/file"; 
import { FileOpener } from "@ionic-native/file-opener"; 
import { FileTransfer,FileTransferObject } from "@ionic-native/file-transfer"; 
import { AppVersion } from "@ionic-native/app-version"; 
import { InAppBrowser} from "@ionic-native/in-app-browser"; 
 ... 
providers: 
[ StatusBar, SplashScreen, 
{provide: ErrorHandler, useClass: IonicErrorHandler}, 
AndroidPermissions, File, AppVersion, FileOpener, FileTransfer, FileTransferObject, NativeService, InAppBrowser
 ] 

// 2 应用
// 新建  src\providers\public\public.ts
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { ConfigProvider } from '../config/config';
import { AlertController } from 'ionic-angular/components/alert/alert-controller';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { File } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { AppVersion } from '@ionic-native/app-version';
import { FileOpener } from '@ionic-native/file-opener';
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { ToastController } from 'ionic-angular/components/toast/toast-controller';
import { Platform } from 'ionic-angular/platform/platform';

/*
  Generated class for the PublicProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class PublicProvider {
  /*公共post提交頭*/
  public httpOptions = {
    headers: new HttpHeaders({ 
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
      "Authorization":  '' ,
    })
  };

  constructor(public http: HttpClient, public config: ConfigProvider
    ,public alertCtrl:AlertController,public loadingCtrl:LoadingController
    ,private transfer: FileTransfer,
    private file: File,private appVersion: AppVersion,private fileOpener:FileOpener
    ,private androidPermissions: AndroidPermissions,public toastCtrl: ToastController,public platform: Platform
  ) {
    // console.log('Hello PublicProvider Provider');
  }
    
  //检查版本更新
  new_version(callback){
    var url = ‘http://www.test.com/test’;
    return this.http.get(url,this.httpOptions).subscribe(function(data){
      callback(data);
    });
  }



  /***** 自动更新APP版本  开始 ******************************/  
  public now_version = '';//当前版本
  public new_app = {//最新版本
    new_version: '',//版本号
    text : '',//更新简介
    url : '',//下载地址
  };

  public has_new : boolean = false;
  get_now_version(){
    var _that = this;
    this.appVersion.getVersionNumber().then(data=>{
      _that.now_version = data;
    });
    return _that.now_version
  }
  check_version(){
    var _that = this;

    //服务器端获取最新版
    this.new_version(data=>{
      _that.new_app.new_version = data.data.version;
      _that.new_app.text = data.data.text;
      _that.new_app.url =  data.data.file_url;
    });

    console.log('_that.new_app');
    console.log(_that.new_app);

    this.appVersion.getVersionNumber().then(data=>{
      _that.now_version = data;
    });

    console.log('_that.now_version = ' + _that.now_version);
  
    //当前版本
    let nowVersionNum = parseInt(this.now_version.toString().replace(new RegExp(/(\.)/g), '0')); 
    // alert('当前版本:'+nowVersionNum);
    let newVersionNum = parseInt(this.new_app.new_version.toString().replace(new RegExp(/(\.)/g), '0'));
    if(nowVersionNum < newVersionNum){
      this.has_new = true;
    }

    console.log('nowVersionNum = ' + nowVersionNum);
    console.log('newVersionNum = ' + newVersionNum);
  }

  presentToast(message: string) {
    let toast = this.toastCtrl.create({message: message, duration: 2000});
    toast.present().then(value => {
      return value;
    });
  }

  autoUpdateApp(){
    setTimeout(() => {

      this.appVersion.getVersionNumber().then(data=>{
        this.now_version = data;
      });
      //服务器端获取最新版
      this.new_version(data=>{
        this.new_app.new_version = data.data.version;
        this.new_app.text = data.data.text;
        this.new_app.url =  data.data.file_url;
        this.updateAPP()
      });

    }, 3000);
  }

  updateAPP(){
    this.check_version()
    //当前版本
    let nowVersionNum = parseInt(this.now_version.toString().replace(new RegExp(/(\.)/g), '0')); 
    // alert('当前版本:'+nowVersionNum);
    let newVersionNum = parseInt(this.new_app.new_version.toString().replace(new RegExp(/(\.)/g), '0')); 
    // alert('最新版本:'+newVersionNum);
    if(nowVersionNum < newVersionNum){
          
      let confirm = this.alertCtrl.create({
        title: '有新版本发布,是否下载更新?',
        message: this.new_app.text,
        buttons: [
          {
            text: '取消',
            handler: () => {
              console.log('Disagree clicked');
              // return false;
              this.check_version()
            }
          },
          {
            text: '确认',
            handler: () => {
              this.permissionsFun()
              //this.download();
            }
          }
        ]
      });
      confirm.present();
    }else{
      this.presentToast('当前已是最新版本');
    }
    
  }

  download(){
    if (this.isAndroid()) {
      var _that = this;
      const fileTransfer: FileTransferObject = this.transfer.create();
      
      //目录创建文件夹 new Date().getTime()
      this.file.createDir(this.file.externalRootDirectory, "martiantoken", false)
      let externalRootDirectory = this.file.externalRootDirectory + 'martiantoken/martiantoken.apk';
      console.log('this.new_app.url')
      console.log(this.new_app.url)

      console.log('externalRootDirectory')
      console.log(externalRootDirectory)


      let num :number = 1;
      fileTransfer.onProgress((event: ProgressEvent) => {
        num =Math.floor(event.loaded/event.total * 100);
      });
      
      let loading = _that.loadingCtrl.create({
        content: '下载进度:'+ num + '%'
      });
      loading.present(); 

      fileTransfer.download(this.new_app.url, externalRootDirectory).then((entry) => {
          // alert('下载成功: ' + entry.toURL());
          _that.fileOpener.open(entry.toURL(),'application/vnd.android.package-archive');
        }, (error) => { 
          
          let confirm = this.alertCtrl.create({
            title: '请开启存储权限',
            message: '权限被拒绝,请在手机设置里手动开启存储权限',
            buttons: [
              {
                text: '取消',
                handler: () => {
                  console.log('Disagree clicked');
                  // return false;
                  //this.check_version()
                  loading.dismiss();
                }
              },
              {
                text: '确认',
                handler: () => {
                  loading.dismiss();
                  this.download();
                }
              }
            ]
          });
          confirm.present();
          
          return false;
        }
      );
    

      

      let timer = setInterval(() => {
          loading.setContent("下载进度:" + num + "%");
          if (num >= 99) {
              clearInterval(timer);
              loading.dismiss();
          }
      }, 300);

    }


    // if (this.isIos()) {
    //   this.openUrlByBrowser("这里边填写下载iOS地址");
    // }


  }


   //检查权限
   permissionsFun(){
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(
      result => {
        if (!result.hasPermission){
          this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE])
            .then(result => {//弹出弹框是否允许
              if(result.hasPermission){//点击允许
                this.download();
                // alert("允许使用LOCATION权限");
              }else{//点击拒绝
                // alert("拒绝使用LOCATION权限");
                //this.platform.exitApp();//退出APP
              }
          });
        }else{
          this.download();
          // alert("已允许位置权限" + result.hasPermission);
        }
  
      },
      err => {
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
      }
  
    );
  }


  /**
   * 通过浏览器打开url
   */
  openUrlByBrowser(url: string): void {
    //this.inAppBrowser.create(url, '_system');
  }

  /**
   * 是否真机环境
   * @return {boolean}
   */
  isMobile(): boolean {
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }

  /**
   * 是否android真机环境
   * @return {boolean}
   */
  isAndroid(): boolean {
    return this.isMobile() && this.platform.is('android');
  }

  /**
   * 是否ios真机环境
   * @return {boolean}
   */
  isIos(): boolean {
    return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
  }

  /***** 自动更新APP版本  结束 ******************************/  
  

}


// app.component.ts

import { Component } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { PublicProvider } from '../providers/public/public';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen,public publicPro: PublicProvider
    
    ) {
    console.log('MyApp-----');
    this.platformReady()
    this.publicPro.autoUpdateApp();
  }

  platformReady() {
    // Call any initial plugins when ready
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.statusBar.overlaysWebView(false);
      this.statusBar.backgroundColorByHexString('#333333');
    });
  }

}



参考网址:https://www.jianshu.com/p/6f88d9c95919

你可能感兴趣的:(ionic3 APP版本更新)