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 ...
随机推荐
- 体育成绩统计——20180801模拟赛T3
体育成绩统计 / Score 题目描述 正所谓“无体育,不清华”.为了更好地督促同学们进行体育锻炼,更加科学地对同学们进行评价,五道口体校的老师们在体育成绩的考核上可谓是煞费苦心.然而每到学期期末时, ...
- centos7下使用wget命令安装mysql
1.首先安装wget命令: yum -y install wget 2.下载mysql wget http://repo.mysql.com/mysql-community-release-el7- ...
- codeigniter 使用
CodeIgniter系列 记录count和分页 对于某个表的不带条件的count,可以简单的用 $total = $this->db->count_all($table_name) 来获 ...
- RxJava Android(RxAndroid) 开发全家桶
RxJava 在 Android 应用开发中越来越流行,但是由于其门槛稍高,初次使用不免遇到很多问题,例如在 RxJava 常见的错误用法 和 不该使用 RxJava 的一些情况 中所描述的情况.为了 ...
- php报错配置问题
在开发的时候php.ini ,要显示所有的错误 error_reporting=E_ALL | E_STRICT 在发布的时候可以显示除了notice之外的错误,打开错误记录功能 error_repo ...
- sublimetext3打造pythonIDE
虽然pycharm是非常好用的pythonIDE,用来开发项目很方便,但是修改调整单个或几个小程序就显得很笨重,这时候我们可以选择使用sublime. 一般来说要开发项目我都用pycharm,开发简单 ...
- 在cmd窗口输入命令遇到You must run this command from a command prompt with administrator privilege怎么办?
点开始菜单,找到Accessories(附件),找到Command Prompt窗口,点右键,选“run as administrator”(以管理员身份运行),之后再执行先前的命令就好了. 2017 ...
- c#课程设计---猜猜看游戏
1:游戏要求 1. 随机显示 一个名字 与 若干张相片(如3张).选择正确的相片. 2. 记录老师对每一个学生的认识概率P.并依据认识概率,确定"猜猜看"游戏中学生出现的频率. 认 ...
- 【X240 QQ视频对方听不到声音】解决方法
[X240 QQ视频对方听不到声音]解决方法: win7为例: 右键点击右下角的"小喇叭"图标,点击"录音设备",显演示样例如以下图: watermark/2/ ...
- python 查询,子查询以及1对多查询
1.添加数据: # 方法1:对象.save() book = Book(**kwargs) book.save() # 方法2:类.create(**kwargs) Book.create(**kwa ...