网络状态 · 小程序 https://developers.weixin.qq.com/miniprogram/dev/api/device.html#wxonnetworkstatuschangecallback

import wepy from 'wepy'
import util from './util'
import md5 from './md5'
// import tip from './tip' const networkStatusChangeLog = () => {
try {
wx.removeStorageSync('onNetworkStatusChange')
} catch (e) {
// Do something when catch error
console.log(e)
}
const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk'
wx.setStorageSync('onNetworkStatusChange', log)
} const isConnected = async () => {
let container = {}
await wx.getNetworkType({
success: function (res) {
container = res
console.log(res)
},
fail: function (res) {},
complete: function (res) {}
})
await wx.onNetworkStatusChange(function (res) {
console.log('onNetworkStatusChange',res)
}) // console.log(container)
// if (!container.networkStatus.isConnected) {
// wx.showToast({
// title: '无网络',
// icon: 'loading',
// duration: 2000
// })
// networkStatusChangeLog()
// return false
// }
return true
} const appendInfo = () => {
const API_SECRET_KEY = 'https://github.com/dyq086/wepy-mall/tree/master/src'
const TIMESTAMP = util.getCurrentTime()
const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase())
const MORE = 'more......'
return {
'API_SECRET_KEY': API_SECRET_KEY,
'TIMESTAMP': TIMESTAMP,
'SIGN': SIGN,
'MORE': MORE
}
} const wxRequest = async (params = {}, url) => {
console.log('wxRequest', params)
const c = await isConnected()
if (!c) {
return
}
// tip.loading()
let data = params.query || {}
const header = params.header || {}
const isAppend = params.isAppend || false
if (isAppend) {
const a = appendInfo()
for (let k in a) {
eval('data.' + k + '= a.' + k)
}
}
let res = await wepy.request({
url: url,
method: params.method || 'GET',
data: data,
header: header
})
// tip.loaded()
console.log('wxRequest', res)
return res
} module.exports = {
wxRequest
}

  

和声明的位置无关,一次声明,整个小程序 都在使用

所以放到

app.wpy?

1、在回调函数中添加本地存储的代码,每次监听到网络状态变化都会在本地记录,然后给用户弹出提醒框;

2、声明一次;

3、在请求网络的公共方法处添加网络状态钩子,方式为读取1中的本地的网络数据。

D:\GPUGO\MP\wepy\mpBMCwepy\src\app.wpy

<style lang="less">
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
}
</style> <script>
import wepy from 'wepy'
import 'wepy-async-function'
import {
setStore
} from 'wepy-redux'
import configStore from './store'
const store = configStore()
setStore(store)
export default class extends wepy.app {
config = {
pages: [
// 'pages/index', 'pages/advertisement', 'pages/companyShow', 'pages/logs', 'pages/materialUpload', 'pages/news', 'pages/questionsAnswers', 'pages/userCenter', 'pages/consumeRecord', 'pages/companyInfo', 'pages/userInfo', 'pages/userLogin', 'pages/videoUpload', 'pages/aboutUs', 'pages/recharge', 'pages/helpCenter', 'pages/commonService', 'pages/cloundAd', 'pages/cloundNews', 'pages/cloundSEM', 'pages/companyQA', 'pages/companyBK', 'pages/shortVideo', 'pages/newsWebView'
'pages/index', 'pages/news', 'pages/userCenter', 'pages/newsWebView', 'pages/userLogin', 'pages/companyInfo', 'pages/personalInfo'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
},
tabBar: {
list: [{
pagePath: 'pages/index',
text: '首wepy',
iconPath: 'images/bar1a.png',
selectedIconPath: 'images/bar1b.png'
},
{
pagePath: 'pages/news',
text: '资讯',
iconPath: 'images/bar2a.png',
selectedIconPath: 'images/bar2b.png'
},
{
pagePath: 'pages/userCenter',
text: '我的',
iconPath: 'images/bar3a.png',
selectedIconPath: 'images/bar3b.png'
}
]
}
}
customData = {
common: {
apiUrl: 'http://api.dev.com:8000/',
imgUrlMP: 'http://blackhole.dev.com/images/',
imgUrlBiz: 'http://api.dev.com:8000/',
dataEyePath: 'http://blackhole.dev.com:50000',
localImgPath: 'http://blackhole.dev.com/images/'
}
}
globalData = {
userInfo: null
}
constructor() {
super()
this.use('requestfix')
this.use('promisify')
}
networkStatusChangeLog() {
const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk'
wx.setStorageSync('onNetworkStatusChangeLog', log)
}
onLaunch() {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
console.log(res)
console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function() {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function() {
// 新的版本下载失败
})
let that = this
wx.onNetworkStatusChange(function(res) {
that.networkStatusChangeLog()
wx.setStorageSync('onNetworkStatusChange', res)
if (!res.isConnected) {
wx.showToast({
title: '无网络',
icon: 'loading',
duration: 2000
})
}
})
}
sleep(s) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise resolved')
}, s * 1000)
})
}
async testAsync() {
const data = await this.sleep(3)
console.log(data)
}
getUserInfo(cb) {
const that = this
if (this.globalData.userInfo) {
return this.globalData.userInfo
}
wepy.getUserInfo({
success(res) {
that.globalData.userInfo = res.userInfo
cb && cb(res.userInfo)
}
})
}
onShareAppMessage(title = 'MBC') {
return {
title: title,
success: function(res) {},
fail: function(res) {}
}
}
}
</script>

  

D:\GPUGO\MP\wepy\mpBMCwepy\src\utils\wxRequest.js

import wepy from 'wepy'
import util from './util'
import md5 from './md5'
// import tip from './tip' const appendInfo = () => {
const API_SECRET_KEY = 'https://github.com/dyq086/wepy-mall/tree/master/src'
const TIMESTAMP = util.getCurrentTime()
const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase())
const MORE = 'more......'
return {
'API_SECRET_KEY': API_SECRET_KEY,
'TIMESTAMP': TIMESTAMP,
'SIGN': SIGN,
'MORE': MORE
}
} const wxRequest = async (params = {}, url) => {
console.log('wxRequest', params)
const c = wx.getStorageSync('onNetworkStatusChange')
if (!c.isConnected) {
wx.showToast({
title: '无网络',
icon: 'loading',
duration: 2000
})
return
}
// tip.loading()
let data = params.query || {}
const header = params.header || {}
const isAppend = params.isAppend || false
if (isAppend) {
const a = appendInfo()
for (let k in a) {
eval('data.' + k + '= a.' + k)
}
}
let res = await wepy.request({
url: url,
method: params.method || 'GET',
data: data,
header: header
})
// tip.loaded()
console.log('wxRequest', res)
return res
} module.exports = {
wxRequest
}

  

    globalData = {
userInfo: null,
onNetworkStatusChangeRes:{}
}
constructor() {
super()
this.use('requestfix')
this.use('promisify')
}
networkStatusChangeLog() {
const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk'
wx.setStorageSync('onNetworkStatusChangeLog', log)
}
onLaunch() {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
console.log(res)
console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function() {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function() {
// 新的版本下载失败
})
let that = this
wx.onNetworkStatusChange(function(res) {
that.networkStatusChangeLog()
that.globalData.onNetworkStatusChangeRes=res
if (!res.isConnected) {
wx.showToast({
title: '无网络',
icon: 'loading',
duration: 2000
})
}
})
}

wx.onNetworkStatusChange(function (res) 监听网络状态变化 实践方案的更多相关文章

  1. Android开发之使用广播监听网络状态变化

    我们经常需要判断网络状态的变化,如有无网络,所以需要监听网络状态的变化,比如网络断开,网络连接给予友好提示.如何监听网络状态的变化呢,最近工作中需要用到这个,于是就用广播机制来实现了网络状态的监听. ...

  2. HTML5判断设备在线离线及监听网络状态变化例子

    经测试android ipad默认的浏览器支持,用appcan封装的网页也支持 本文原创,转载请说明出处 <!doctype html> <html> <head> ...

  3. HTML5外包团队——技术分享:HTML5判断设备在线离线及监听网络状态变化例子

    <!doctype html> <html> <head> <meta http-equiv="content-type" content ...

  4. Android 动态监听网络 断网重连

    需求: 网络连接断开 弹出popupwindow 当前网络连接断开 网络恢复时popupwindow 消失重新请求网络. 需求描述完毕 上一张帅图 思路:广播 发送及时消息 断网flag  popup ...

  5. 10.22 tcpdump:监听网络流量

    [功能说明] tcpdump命令是一个截获网络数据包的包分析工具.tcpdump可以将网络中传送的数据包的“头”完全截获下来以提供分析.它支持针对网络层.协议.主机.端口等的过滤,并支持与.或.非逻辑 ...

  6. ionic app 监听网络功能

    安装cordova插件: cordova plugin add cordova-plugin-network-information 在app.js 的run()里面的function()注入$cor ...

  7. html5 js 监听网络在线与离线

    <!doctype html> <html> <head> <meta http-equiv="content-type" content ...

  8. 通过BroadCast与service时时监听网络变化

    首先需要一个service: 这里我定义了一个NetworkStateService,在这个service中我写了一个BroadcastReceiver用于监听网络状态发生改变的情况并在这个servi ...

  9. android动态注册监听网络变化异常

    在使用广播接收器监听网络变化的时候,在AndroidManifest.xml中加入<user-permission android:name="android.permission.A ...

随机推荐

  1. 判断图连通的三种方法——dfs,bfs,并查集

    Description 如果无向图G每对顶点v和w都有从v到w的路径,那么称无向图G是连通的.现在给定一张无向图,判断它是否是连通的. Input 第一行有2个整数n和m(0 < n,m < ...

  2. 记一次kubernetes集群异常: kubelet连接apiserver超时

    Background kubernetes是master-slave结构,master node是集群的大脑, 当master node发生故障时整个集群都"out of control&q ...

  3. Atom打开大文件卡死的问题替代方案

    无解,本身是网页的框架,所以直接换回ST或者Notepad++吧.

  4. MySQL GUI Tools 使用简介

    转自:http://database.ctocio.com.cn/422/8919922.shtml    MySQL GUI Tools是一套图形化桌面应用工具套装,可以用来管理MySQL服务器.该 ...

  5. {dede:sql}标签的用法

    sql标签可以称得上是个万能标签了,查询数据库将其输出,这里介绍一些关于这个标签的用法: 1.用来输出统计内容,这个是不错的,举个例子,我们来统计下总共发了多少的文章,思路就是输出dede_addon ...

  6. ArcGIS教程:公布地理处理服务

    要公布地理处理服务.您须要两个元素:结果 窗体中的结果和到 ArcGIS Server 的管理员或公布者连接. 要公布服务,请右键单击结果并选择共享为 > 地理处理服务.例如以下图所看到的.此操 ...

  7. kali渗透测试基础

    一侦查 研究如何收集有关目标的情报,比如开发那些端口用来通信,托管在哪里,提供给客户的服务类型等. 交付内容应该包括需要攻击的所有目标资产清单,与那些资产关联的应用,使用的服务以及可能的资产所有者. ...

  8. z pre-pass 相关问题的讨论

    z pre-pass 是指在渲染流程中,第一个pass先画一张深度buffer出来,得到需要绘制的最前面这层深度,用这个在接下来的pass中做深度剔出,这样在第二个pass中会省略很多绘制. 这项技术 ...

  9. Linux多线程编程-信号量

    在Linux中.信号量API有两组.一组是多进程编程中的System V IPC信号量.另外一组是我们要讨论的POSIX信号量. 这两组接口类似,但不保证互换.POSIX信号量函数都已sem_开头,并 ...

  10. js 展开&收缩 二种

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...