wx.onNetworkStatusChange(function (res) 监听网络状态变化 实践方案
网络状态 · 小程序 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) 监听网络状态变化 实践方案的更多相关文章
- Android开发之使用广播监听网络状态变化
我们经常需要判断网络状态的变化,如有无网络,所以需要监听网络状态的变化,比如网络断开,网络连接给予友好提示.如何监听网络状态的变化呢,最近工作中需要用到这个,于是就用广播机制来实现了网络状态的监听. ...
- HTML5判断设备在线离线及监听网络状态变化例子
经测试android ipad默认的浏览器支持,用appcan封装的网页也支持 本文原创,转载请说明出处 <!doctype html> <html> <head> ...
- HTML5外包团队——技术分享:HTML5判断设备在线离线及监听网络状态变化例子
<!doctype html> <html> <head> <meta http-equiv="content-type" content ...
- Android 动态监听网络 断网重连
需求: 网络连接断开 弹出popupwindow 当前网络连接断开 网络恢复时popupwindow 消失重新请求网络. 需求描述完毕 上一张帅图 思路:广播 发送及时消息 断网flag popup ...
- 10.22 tcpdump:监听网络流量
[功能说明] tcpdump命令是一个截获网络数据包的包分析工具.tcpdump可以将网络中传送的数据包的“头”完全截获下来以提供分析.它支持针对网络层.协议.主机.端口等的过滤,并支持与.或.非逻辑 ...
- ionic app 监听网络功能
安装cordova插件: cordova plugin add cordova-plugin-network-information 在app.js 的run()里面的function()注入$cor ...
- html5 js 监听网络在线与离线
<!doctype html> <html> <head> <meta http-equiv="content-type" content ...
- 通过BroadCast与service时时监听网络变化
首先需要一个service: 这里我定义了一个NetworkStateService,在这个service中我写了一个BroadcastReceiver用于监听网络状态发生改变的情况并在这个servi ...
- android动态注册监听网络变化异常
在使用广播接收器监听网络变化的时候,在AndroidManifest.xml中加入<user-permission android:name="android.permission.A ...
随机推荐
- BZOJ1801 [Ahoi2009]chess 中国象棋(DP, 计数)
题目链接 [Ahoi2009]chess 中国象棋 设$f[i][j][k]$为前i行,$j$列放了1个棋子,$k$列放了2个棋子的方案数 分6种情况讨论,依次状态转移. #include <b ...
- 解决php中redis client进行subscribe操作出现timeout的问题
出现该问题的原因是poll设置接收超时所致,这个超时默认设置60s 设置Redis::OPT_READ_TIMEOUT配置项: 解决方法如下: <?php $redis = new Redis( ...
- schema设计
Schema设计 Schema:表的模式: 设计数据的表,索引,以及表和表的关系 在数据建模的基础上将关系模型转为数据库表 满足业务模型需要基础上根据数据库和应用特点优化表结构 关系模型图 ...
- 2013年9月29日 iOS 周报
新闻 Apple Tech Talks 2013 在中国上海的iOS Tech Talks活动将于11月12日展开,活动主要针对iOS 7.活动分为App开放日和游戏开放日,主要内容可查看链接.当你看 ...
- void*类型的指针
void*是一种特殊的指针类型,可以用来存放任意对象的地址.一个void*指针存放着一个地址,这一点和其他指针类似.不同的是,我们对它到底储存的是什么对象的地址并不了解: 比如:double a=2. ...
- ASP.NET Web API是如何根据请求选择Action的?[上篇] 【转】
http://www.cnblogs.com/leo_wl/p/3316548.html ASP.NET Web API是如何根据请求选择Action的?[上篇] Web API的调用请求总是针对定义 ...
- Web编程前端之7:web.config详解 【转】
http://www.cnblogs.com/alvinyue/archive/2013/05/06/3063008.html 声明:这篇文章是摘抄周公(周金桥)的<asp.net夜话> ...
- SpringMVC项目中web.xml中的节点载入顺序问题
SpringMVC项目中web.xml中的节点载入顺序问题,之前以为web.xml中就是一些配置信息,和节点的顺序没有关系.后来才发现初始化时的载入顺序是和节点的顺序相关的. 完整的web.xml文件 ...
- MyBatis-Invalid bound statement (not found)-问题处理
最近把工程改为Hibernate和MyBatis并存,并存只要注意两点即可: 1.使用同一个dataSource 2.事物交给Hibernate进行管理(Hibernate4+) Hibernate ...
- Oracle递归操作
需求:找出代理商中没有挂商家的代理商 简单SQL如下: select * from t_proxy tp where tp.id not in (SELECT tp.id as p_id FROM t ...