微信小程序,延时执行js函数的问题

微信小程序,延时执行js函数的问题,第1张

fight:function(e){

   that = this;

   thatsetData({

      buttondisabled: true,

      loading: true

   });     //<--这里是分号不是逗号

   setTimeout(function(){

      thatsetData({

         buttondisplay: 'none',

         playerdisplay: 'block'

      })        //这里的错误不太好描述,自己看了

   }, 9000);

}

可以把微信小程序隐藏起来。

打开微信“我”的页面,然后打开“设置”

2 然后点开设置,在设置页面有个“通用”

3 点开通用,再点开“发现页管理”

4 打开发现页管理,把“小程序”关掉

5 这样再返回“发现”页面看,就看不见小程序啦,”小程序“已经被隐藏了

微信小程序 拍照和相机选择详解

前言:

小程序中获取可通过两种方式得到,第一种是直接打开微信内部自己的样式,第一格就是相机拍照,后面是,第二种是d框提示用户是要拍照还是从相册选择,下面一一来看。

选择相册要用到wxchooseImage(OBJECT)函数,具体参数如下:

直接来看打开相机相册的代码:

Page({   data: {    tempFilePaths: ''   },   onLoad: function () {   },   chooseimage: function () {    var that = this;    wxchooseImage({     count: 1, // 默认9      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有      success: function (res) {      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示       thatsetData({       tempFilePaths: restempFilePaths      })     }    })     },          })      

方法一效果图如下:

个人认为第二种用户体验要好一点,效果如下:

点击获取d框提示,代码如下:

Page({   data: {    tempFilePaths: ''   },   onLoad: function () {   },   chooseimage: function () {    var that = this;    wxshowActionSheet({     itemList: ['从相册中选择', '拍照'],     itemColor: "#CED63A",     success: function (res) {      if (!rescancel) {       if (restapIndex == 0) {        thatchooseWxImage('album')       } else if (restapIndex == 1) {        thatchooseWxImage('camera')       }      }     }    })     },     chooseWxImage: function (type) {    var that = this;    wxchooseImage({     sizeType: ['original', 'compressed'],     sourceType: [type],     success: function (res) {      consolelog(res);      thatsetData({       tempFilePaths: restempFilePaths[0],      })     }    })   }      })      

文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wxsaveFile,在小程序下次启动时才能访问得到。

布局文件:

<button style="margin:30rpx;" bindtap="chooseimage">获取</button>  <image src="{{tempFilePaths }}" catchTap="chooseImageTap" mode="aspectFit" style="width: 100%; height: 450rpx" />    

在微信小程序实现简单定位功能,简单易读,获取经纬度信息,在pages下创建一个单页,举例如local页面,配置该类页面的js、wxml、json文件,来完成定位api接口的引用

localjs如下

var app = getApp()  

Page({ 

    data:{

       latitude:'',

       longitude:''

    },

getLocation:function(e) {

    consolelog(e)

    var that = this

    wxgetLocation({

      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wxopenLocation 的坐标

      success: function(res){

        consolelog(res)     

      thatsetData({

              longitude:reslongitude,

              latitude:reslatitude        

      })

    }

 })

}

})

localwxml如下

<view class="page-body">

<view class="page-body-form">

    <text class="page-body-form-key">经度:</text>

    <input class="page-body-form-value" type="text" 

    value="{{longitude}}" name="longitude"></input>

    <text class="page-body-form-key">纬度:</text>

    <input class="page-body-form-value" type="text" 

    value="{{latitude}}" name="latitude"></input>  

    <view class="page-body-buttons">

    <button class="page-body-button" type="primary" 

    bindtap="getLocation">获取位置</button>

    </view>

</view>

</view>

appjson如下

{

  "pages":[

    "pages/local/local"

  ],

  "window":{

    "backgroundTextStyle":"light",

    "navigationBarBackgroundColor": "#fff",

    "navigationBarTitleText": "定位",

    "navigationBarTextStyle":"black"

  }

}

#使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程

#在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求

#1首先是要初始化蓝牙:openBluetoothAdapter()

```js

if (wxopenBluetoothAdapter) {

wxopenBluetoothAdapter({

        success: function(res) {

            / 获取本机的蓝牙状态 /

            setTimeout(() => {

                getBluetoothAdapterState()

            }, 1000)

        },

        fail: function(err) {

            // 初始化失败

        }

    })

    } else {    

    }

```

#2检测本机蓝牙是否可用:

#  要在上述的初始化蓝牙成功之后回调里调用

```js

getBluetoothAdapterState() {

    var that= this;

    thattoastTitle= '检查蓝牙状态'

wxgetBluetoothAdapterState({

        success: function(res) {

startBluetoothDevicesDiscovery()

},

        fail(res) {

            consolelog(res)

}

})

}

```

#3 开始搜索蓝牙设备

```js

startBluetoothDevicesDiscovery() {

    var that= this;

    setTimeout(() => {

wxstartBluetoothDevicesDiscovery({

            success: function(res) {

/ 获取蓝牙设备列表 /

                thatgetBluetoothDevices()

},

            fail(res) {

}

})

}, 1000)

}

```

#4 获取搜索到的蓝牙设备列表

# / thatdeviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙/

```js

getBluetoothDevices() {

    var that= this;

    setTimeout(() => {

wxgetBluetoothDevices({

            services: [],

            allowDuplicatesKey: false,

            interval: 0,

            success: function(res) {

                if (resdeviceslength> 0) {

                    if (JSONstringify(resdevices)indexOf(thatdeviceName) !== -1) {

                        for (let i = 0; i < resdeviceslength; i++) {

                            if (thatdeviceName === resdevices[i]name) {

/ 根据指定的蓝牙设备名称匹配到deviceId /

                                thatdeviceId = thatdevices[i]deviceId;

                                setTimeout(() => {

                                    thatconnectTO();

}, 2000);

};

};

} else {

}

} else {

}

},

            fail(res) {

                consolelog(res, '获取蓝牙设备列表失败=====')

}

})

}, 2000)

},

```

#5连接蓝牙

# 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务

```js

connectTO() {

wxcreateBLEConnection({

        deviceId: deviceId,

        success: function(res) {

            thatconnectedDeviceId = deviceId;

/ 4获取连接设备的service服务 /

thatgetBLEDeviceServices();

wxstopBluetoothDevicesDiscovery({

                success: function(res) {

                    consolelog(res, '停止搜索')

},

                fail(res) {

}

})

},

        fail: function(res) {

}

})

}

```

#6 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值

```js

getBLEDeviceServices() {

    setTimeout(() => {

wxgetBLEDeviceServices({

            deviceId: thatconnectedDeviceId,

            success: function(res) {

                thatservices= resservices

/ 获取连接设备的所有特征值 /

thatgetBLEDeviceCharacteristics()

},

            fail: (res) => {

}

})

}, 2000)

},

```

#7获取蓝牙设备特征值

# 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id,

```js

getBLEDeviceCharacteristics() {

            setTimeout(() => {

wxgetBLEDeviceCharacteristics({

                    deviceId: connectedDeviceId,

                    serviceId: services[2]uuid,

                    success: function(res) {

                        for (var i = 0; i < rescharacteristicslength; i++) {

                            if ((rescharacteristics[i]propertiesnotify || rescharacteristics[i]propertiesindicate) &&

                                (rescharacteristics[i]propertiesread && rescharacteristics[i]propertieswrite)) {

                                consolelog(rescharacteristics[i]uuid, '蓝牙特征值 ==========')

/ 获取蓝牙特征值 /

                                thatnotifyCharacteristicsId = rescharacteristics[i]uuid

// 启用低功耗蓝牙设备特征值变化时的 notify 功能

thatnotifyBLECharacteristicValueChange()

}

}

},

                    fail: function(res) {

}

})

}, 1000)

},

```

#8启动notify 蓝牙监听功能 然后使用 wxonBLECharacteristicValueChange用来监听蓝牙设备传递数据

#接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换

```js

notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能

            var that= this;

            consolelog('6启用低功耗蓝牙设备特征值变化时的 notify 功能')

wxnotifyBLECharacteristicValueChange({

                state: true,

                deviceId: thatconnectedDeviceId,

                serviceId: thatnotifyServicweId,

                characteristicId: thatnotifyCharacteristicsId,

                complete(res) {

/用来监听手机蓝牙设备的数据变化/

wxonBLECharacteristicValueChange(function(res) {

//

                        thatbalanceData += thatbuf2string(resvalue)

                        thathexstr += thatreceiveData(resvalue)

})

},

                fail(res) {

                    consolelog(res, '启用低功耗蓝牙设备监听失败')

                    thatmeasuringTip(res)

}

})

},

/转换成需要的格式/

buf2string(buffer) {

                    var arr = Arrayprototypemapcall(new Uint8Array(buffer), x => x)

                    return arrmap((char, i) => {

                        return StringfromCharCode(char);

                    })join('');

},

receiveData(buf) {

return thishexCharCodeToStr(thisab2hex(buf))

},

/转成二进制/

ab2hex (buffer) {

              var hexArr = Arrayprototypemapcall(

                  new Uint8Array(buffer), function (bit) {

                      return ('00' + bittoString(16))slice(-2)

}

)

              return hexArrjoin('')

},

/转成可展会的文字/

hexCharCodeToStr(hexCharCodeStr) {

              var trimedStr = hexCharCodeStrtrim();

              var rawStr = trimedStrsubstr(0, 2)toLowerCase() === '0x' trimedStrsubstr(2) : trimedStr;

              var len = rawStrlength;

              var curCharCode;

              var resultStr= [];

              for (var i = 0; i < len; i = i+ 2) {

                  curCharCode = parseInt(rawStrsubstr(i, 2), 16);

                  resultStrpush(StringfromCharCode(curCharCode));

}

              return resultStrjoin('');

},

```

# 向蓝牙设备发送数据

```js

sendData(str) {

    let that= this;

    let dataBuffer = new ArrayBuffer(strlength)

    let dataView = new DataView(dataBuffer)

    for (var i = 0; i < strlength; i++) {

        dataViewsetUint8(i, strcharAt(i)charCodeAt())

}

    let dataHex = thatab2hex(dataBuffer);

    thiswriteDatas = thathexCharCodeToStr(dataHex);

wxwriteBLECharacteristicValue({

        deviceId: thatconnectedDeviceId,

        serviceId: thatnotifyServicweId,

        characteristicId: thatnotifyCharacteristicsId,

        value: dataBuffer,

        success: function (res) {

            consolelog('发送的数据:' + thatwriteDatas)

            consolelog('message发送成功')

},

        fail: function (res) {

},

        complete: function (res) {

}

})

},

```

# 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块

```js

// 断开设备连接

closeConnect() {

if (thatconnectedDeviceId) {

wxcloseBLEConnection({

            deviceId: thatconnectedDeviceId,

            success: function(res) {

thatcloseBluetoothAdapter()

},

            fail(res) {

}

})

} else {

thatcloseBluetoothAdapter()

}

},

// 关闭蓝牙模块

closeBluetoothAdapter() {

wxcloseBluetoothAdapter({

        success: function(res) {

},

        fail: function(err) {

}

})

},

```

#在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题

#今天的蓝牙使用心得到此结束,谢谢

// appjs

doLogin() {

    if (!wxgetStorageSync("userid") && !wxgetStorageSync("token")) {

        // 登录

        wxlogin({

            success: res => {

                //自己的后台

                

这样能解决不?也是看别人的代码,就是用计时器setInterval每隔100毫秒执行一次,看看登录信息拿到没有,拿到了,在进行后续 *** 作。

以上就是关于微信小程序,延时执行js函数的问题全部的内容,包括:微信小程序,延时执行js函数的问题、微信小程序怎么写显示和隐藏效果、微信小程序开发时如何调用本地图片等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zz/9275266.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-26
下一篇2023-04-26

发表评论

登录后才能评论

评论列表(0条)

    保存