uniApp开发微信小程序-连接蓝牙连接打印机上岸!

历经波折三次成功上岸!

三次经历简单絮叨一下:使用uniApp+vue开发的微信小程序,使用蓝牙连接打印机,蓝牙所有的接口都是插件中封装的,用的插件市场中的这个: dothan-lpapi-ble ;所以,开发中,主要是看插件文档中使用的API。

首次上线

情况说明: 首次上线微信小程序:直接初始化实例,调用的插件API,测试环境成功连接打印,就上线了。

结果

复制代码
客户手机一直搜索不到打印机,根据经验发现没执行实例的代码;
想到授权蓝牙也没自动弹框提示,小程序设置中也没有蓝牙开启设置;

问题定位:

复制代码
那就问 deepseeek 开干呗!
1. 可能是用户手机 鸿蒙系统 问题:在系统设置中找到应用管理,找到微信,然后打开微信的权限管理,查看 附近设备的权限 - 开启(反复开关)。
  1. 显示授权:必要的权限声明

  2. 检查manifest.json配置

  3. 微信小程序发版后台 - 设置 - 基本设置 - 服务内容声明 - 用户隐私保护指引 - 添加(蓝牙、微信信息收集)

二次上线

情况说明: 二次上线微信小程序:提交审核是其他同事在做,正常提交

结果

复制代码
客户手机一直搜索不到打印机,根据经验发现没执行实例的代码;
线上环境用户还是没有触发授权蓝牙、位置信息提示;
审核没通过

问题定位:

复制代码
1. 提交审核时勾选了:未采集用户隐私
2. 亲自提审、加图片、视频辅佐

三次上线

情况说明:审核通过

结果

复制代码
线上成功授权、成功搜索打印机!

成功版本代码

manifest.json配置

json 复制代码
"mp-weixin": {
		"appid": "...",
		//  添加...
		"permission": {
			"scope.bluetooth": {
				"desc": "用于连接蓝牙设备"
			},
			"scope.userLocation": {
				"desc": "你的位置信息将用于蓝牙设备连接"
			}
		},
		"requiredPrivateInfos": ["getLocation"]
	},
	

授权提示 - deepseek友情提供

javascript 复制代码
// 使用-获取蓝牙权限
await this.bringBluetoothRight();

// 方法 methods: 
bringBluetoothRight() {
  let _this = this;

  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: async (res) => {
        try {
          console.log(res, 'res')
          // 1. 同时检查蓝牙和位置权限
          const needBluetooth = !res.authSetting['scope.bluetooth'];
          const needLocation = !res.authSetting['scope.userLocation'];

          if (!needBluetooth && !needLocation) {
            // 已有全部权限
            return resolve(await _this.wechatBluetoothAuthUtils());
          }

          // 2. 显示预授权提示(合并说明)
          await _this.showPreAuthorizeModal(
            '需要蓝牙和位置权限',
            '连接打印机需要以下权限:\n\n1. 蓝牙权限 - 用于设备配对\n2. 位置权限 - 用于搜索设备'
          );

          // 3. 按顺序请求权限
          if (needBluetooth) {
            await _this.requestPermission('scope.bluetooth', '蓝牙');
          }

          if (needLocation) {
            await _this.requestPermission('scope.userLocation', '位置');
          }

          // 4. 验证权限获取结果
          const currentSettings = await _this.getSettingWithRetry();

          console.log(currentSettings, 'currentSettings')
          if ((!needBluetooth || currentSettings['scope.bluetooth']) &&
              (!needLocation || currentSettings['scope.userLocation'])) {
            console.log('.......')
            resolve(await _this.wechatBluetoothAuthUtils());
          } else {
            console.log('1111111')
            // 5. 有权限未被授予,引导去设置页
            await _this.showGoSettingModal();
            const finalSettings = await _this.getSettingWithRetry();

            if ((!needBluetooth || finalSettings['scope.bluetooth']) &&
                (!needLocation || finalSettings['scope.userLocation'])) {
              resolve(await _this.wechatBluetoothAuthUtils());
            } else {
              reject(new Error('权限未完全授予'));
            }
          }
        } catch (error) {
          reject(error);
        }
      },
      fail: reject
    });
  });
},
// 新增:带重试的获取设置
getSettingWithRetry(retry = 2) {
  return new Promise((resolve, reject) => {
    const tryGet = (attempt) => {
      uni.getSetting({
        success: resolve,
        fail: attempt > 0 ?
          () => setTimeout(() => tryGet(attempt - 1), 500) : reject
      });
    };
    tryGet(retry);
  });
},

// 改进:通用权限请求方法
requestPermission(scope, permissionName) {
  let _this = this;
  // 添加最大重试次数控制
  const MAX_RETRY = 1; // 最多重试1次(即总共2次机会)

  return new Promise((resolve, reject) => {
    const tryAuthorize = (retryCount = 0) => {
      uni.authorize({
        scope,
        success: resolve,
        fail: async () => {
          // 第一次拒绝时显示提示,后续直接引导去设置页
          if (retryCount < MAX_RETRY) {
            const confirmed = await _this.showPreAuthorizeModal(
              `${permissionName}权限被拒绝`,
              `需要${permissionName}权限才能连接打印机,是否重新授权?`,
              '重新授权',
              '取消'
            );

            if (confirmed) {
              tryAuthorize(retryCount + 1); // 增加重试计数
              return;
            }
          }

          // 达到最大重试或用户取消,引导去设置页
          const goSetting = await _this.showPreAuthorizeModal(
            '权限不足',
            `需要${permissionName}权限才能使用打印机功能,是否去设置页开启?`,
            '去设置',
            '暂不开启'
          );

          if (goSetting) {
            uni.openSetting({
              success: (res) => {
                res.authSetting[scope] ? resolve() :
                  reject(new Error(
                    `用户未授权${permissionName}权限`));
              },
              fail: () => reject(new Error('打开设置页失败'))
            });
          } else {
            reject(new Error(`用户取消${permissionName}权限授权`));
          }
        }
      });
    };

    tryAuthorize(); // 开始首次授权尝试
  });
},
// 改进:预授权弹窗(返回Promise<boolean>)
showPreAuthorizeModal(title, content) {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      confirmText: '继续',
      cancelText: '取消',
      success: (res) => {
        resolve(!!res.confirm);
      },
      fail: () => resolve(false)
    });
  });
},

// 改进:去设置页弹窗
showGoSettingModal() {
  return this.showPreAuthorizeModal(
    '需要权限',
    '需要前往设置页手动开启权限,是否现在去设置?'
  ).then((confirm) => {
    if (confirm) {
      return new Promise((resolve) => {
        uni.openSetting({
          success: resolve,
          fail: resolve
        });
      });
    }
    return Promise.reject(new Error('用户取消设置'));
  });
},


wechatBluetoothAuthUtils() {
  let _this = this;
  const {
    bluetoothEnabled,
    platform
  } = uni.getSystemInfoSync();
  console.log(bluetoothEnabled,
              platform)
  // 设备为IOS时,微信蓝牙是否开启
  if (platform === 'ios') {
    return new Promise((resolve, reject) => {
      // 初始化蓝牙模块(用openBluetoothAdapter 方法解决部分ios设备,授权蓝牙失败的问题)
      uni.openBluetoothAdapter({
        success: () => {
          // 开启蓝牙功能 =》 初始化拾果sdk
          resolve(true);
        },
        fail: (openBlueFail) => {
          if (openBlueFail.state === 3) {
            // 说明微信应用蓝牙未授权
            uni.showModal({
              content: '检测到您未允许微信访问手机蓝牙权限,是否打开系统设置?',
              showCancel: false,
              confirmText: '前往设置',
              success: () => {
                // 跳转微信应用权限
                uni.openAppAuthorizeSetting();
              },
            });
          } else if (openBlueFail.state === 4) {
            // 说明系统蓝牙未开启
            uni.showModal({
              content: '蓝牙设置 - 小程序需要通过蓝牙搜索和连接设备,请确认手机蓝牙功能是否已开启?',
              showCancel: false,
              confirmText: '我已开启',
              success: async () => {
                const {
                  bluetoothEnabled,
                  platform
                } = uni.getSystemInfoSync();
                if (bluetoothEnabled) {
                  // 开启蓝牙功能
                  resolve(true);
                } else {
                  uni.showToast({
                    icon: 'none',
                    title: '手机蓝牙未开启'
                  })
                }
              },
            });
          }
        },
      });
    });
  } else {
    return new Promise(function(resolve, reject) {
      // andriod
      if (!bluetoothEnabled) {
        // 说明系统蓝牙未开启
        uni.showModal({
          content: '蓝牙设置 - 小程序需要通过蓝牙搜索和连接设备,请确认手机蓝牙功能是否已开启?',
          showCancel: false,
          confirmText: '我已开启',
          success: async () => {
            const {
              bluetoothEnabled,
              platform
            } = uni.getSystemInfoSync();
            if (bluetoothEnabled) {
              // 开启蓝牙功能
              resolve(true);
            } else {
              toast({
                title: '手机蓝牙未开启'
              });
            }
          },
        });
      } else {
        // 开启蓝牙功能
        resolve(true);
      }
    });
  }
},

额外关闭提示:

javascript 复制代码
<button class="search-btn" type="default" @click="toggleLocationTracking">{{ isTrackingLocation ? '关闭位置追踪' : '开启位置追踪' }}</button>

// data
isTrackingLocation:false

// methods
toggleLocationTracking() {
				if (this.isTrackingLocation) {
					this.stopLocationTracking();
				} else {
					this.startLocationTracking();
				}
			},
startLocationTracking() {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						this.isTrackingLocation = true;
						uni.showToast({
							title: '已开启位置服务',
							icon: 'success'
						});
					},
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '需要位置权限才能搜索蓝牙设备',
							confirmText: '去设置',
							success: (res) => {
								if (res.confirm) uni.openSetting();
							}
						});
					}
				});
			},
stopLocationTracking() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation']) {
							uni.showModal({
								title: '确认',
								content: '确定要关闭位置服务吗?关闭后将无法搜索新设备',
								success: (res) => {
									if (res.confirm) {
										// 实际微信小程序无法直接关闭权限,引导用户去设置页
										uni.openSetting({
											success: () => {
												this.isTrackingLocation = false;
											}
										});
									}
								}
							});
						}
					}
				});
			},
								
相关推荐
FinClip2 小时前
凡泰极客亮相QCon2025鸿蒙专场,解析FinClip“技术+生态”双引擎
微信小程序
Good Lucky4 小时前
Skyline配置指南-微信小程序
chrome·微信小程序·小程序·skyline
前端开发呀5 小时前
无所不能的uniapp拦截器
前端·uni-app
code袁5 小时前
基于微信小程序的校园跑腿系统的设计与实现
微信小程序·小程序·校园跑腿小程序·notepad++·小程序开发·校园跑腿小程序开发
0x046 小时前
微信小程序上传图片后立即展示该图片的最佳实践
前端·微信小程序
weixin_443566477 小时前
uniapp离线打包提示未添加videoplayer模块
uni-app
Good Lucky8 小时前
禁止页面滚动的方法-微信小程序
微信小程序·小程序
WEIII10 小时前
不是?全网都找不到案例?小程序集成 gifsicle wasm
前端·微信小程序·webassembly
山海青风12 小时前
微信小程序实战案例 - 餐馆点餐系统 阶段1 - 菜单浏览
微信小程序·小程序