cordova插件network判断网络状态

一、安装插件

ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

二、引入

app.module.ts 里引入插件

import {
    
     Network } from "@ionic-native/network/ngx";
 
providers: [
    Network
]

先在app.module.ts里引入插件

三、使用(在使用页面引入)

import {
    
     Network } from '@ionic-native/network';
 
 constructor(
    public network:Network
  ) {
    
    
    this.netWork() 
  }
netWork(){
    
    
    // 当网络状态发生改变时触发当前方法
    // network.type返回值:unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none
    this.network.onConnect().subscribe(
        (res)=>{
    
    
            console.log(‘res’ + this.network.type);
            //判断手机状态是否联网,如果返回状态为none,则证明网络断开,弹框提醒
			if(this.network.type === 'none'){
    
    
				//ionic5自带提示框组件
	          const alert = await this.alertController.create({
    
    
	            header: "提示",
	            message: '请检查您的网络',
	            cssClass: "alertCustomCss",
	            buttons: ["确定"],
	          });
	          await alert.present();
	          
        }else{
    
    
        	//网络状态没问题后,调用后续自己要进行的方法
            this.timeStatus();
        	}
        }
        (err)=>{
    
    
        	console.log(‘err’ + this.network.type);
        }
    )
}

四、注意事项

4.1 网络状态network.type返回值:

unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none

4.2 断开网络!!!

断开网络,network.type返回值为none,但它走的还是成功回调,详情请查找代码,“请检查您的网络状态”放在的位置。

猜你喜欢

转载自blog.csdn.net/wangjiecsdn/article/details/117365584