更新记录
1.0.1(2025-12-13) 下载此版本
✨ 新增功能
应用版本管理
- ✅ 检查应用更新(checkAppUpdate)
- ✅ 显示系统原生更新对话框(showUpdateDialog)
- ✅ 一键式自动更新(autoCheckUpdate)
- ✅ 获取当前应用版本信息(getCurrentAppVersion)
- ✅ 支持 Promise 和回调两种调用方式
屏幕方向控制
- ✅ 设置屏幕方向(setScreenOrientation)
- ✅ 获取当前屏幕方向(getScreenOrientation)
- ✅ 锁定当前方向(lockOrientation)
- ✅ 重置为默认方向(resetOrientation)
系统服务跳转
- ✅ 跳转到系统设置页面(openSystemSettings)
- ✅ 跳转到应用商城评论页(openAppGalleryReview)
1.0.0(2025-11-20) 下载此版本
初步提交
平台兼容性
uni-app(4.71)
| Vue2 | Vue3 | Vue2插件版本 | Chrome | Safari | app-vue | app-vue插件版本 | app-nvue | Android | iOS | 鸿蒙 | 鸿蒙插件版本 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| - | √ | 1.0.0 | × | × | √ | 1.0.0 | - | - | - | 5.0.0 | 1.0.0 |
| 微信小程序 | 支付宝小程序 | 抖音小程序 | 百度小程序 | 快手小程序 | 京东小程序 | 鸿蒙元服务 | QQ小程序 | 飞书小程序 | 快应用-华为 | 快应用-联盟 |
|---|---|---|---|---|---|---|---|---|---|---|
| × | × | × | × | × | × | × | × | × | × | × |
uni-app x(4.71)
| Chrome | Safari | Android | iOS | 鸿蒙 | 微信小程序 |
|---|---|---|---|---|---|
| - | - | - | - | - | - |
harmony-auth
华为账号登录 & 鸿蒙系统服务 UTS 原生插件
一个功能完整的 HarmonyOS 原生插件,提供华为账号授权登录---
🚀 快速开始
1. 安装插件
方式一:HBuilderX 插件市场
- 在 HBuilderX 中打开项目
- 进入插件市场搜索
harmony-auth - 点击安装到项目
方式二:手动安装
将插件文件夹复制到项目的 uni_modules/ 目录下
2. 配置权限
在 manifest.json 中配置所需权限:
{
"app-harmony": {
"permissions": [
"ohos.permission.INTERNET",
"ohos.permission.GET_NETWORK_INFO"
]
}
}
3. 华为开发者配置
- 登录 华为开发者联盟
- 创建应用并配置:
- 应用包名(bundleName)
- 应用签名指纹(SHA256)
- 启用账号服务(Account Kit)
- 启用推送服务(Push Kit)- 如需使用推送功能
- 下载
agconnect-services.json配置文件
4. 导入使用
// 账号认证相关
import {
getQuickLoginAnonymousPhone, // 获取匿名手机号
setScreenOrientation, // 设置屏幕方向
openSystemSettings // 打开系统设置
} from '@/uni_modules/harmony-auth';
// 版本更新相关
import {
checkAppUpdate, // 检查更新
showUpdateDialog, // 显示更新对话框
autoCheckUpdate, // 自动检查更新
getCurrentAppVersion // 获取当前版本
} from '@/uni_modules/harmony-auth';
// 推送服务相关
import {
initHarmonyPush, // 初始化推送
getPushToken, // 获取推送Token
onPushMessage, // 监听推送消息
receivePushMessage // 接收推送消息(供原生调用)
} from '@/uni_modules/harmony-auth';
```屏幕方向控制等核心功能。
---
## 📦 插件信息
| 属性 | 值 |
|------|-----|
| **插件ID** | `harmony-auth` |
| **版本** | `1.0.0` |
| **平台支持** | HarmonyOS (app-harmony) |
| **插件类型** | UTS 原生插件 |
| **开发框架** | uni-app-x / uni-app |
| **最低HBuilderX版本** | 3.6.8+ |
---
## ✨ 功能特性
### 🔐 华为账号认证
- ✅ **获取匿名手机号** - 获取华为账号绑定的脱敏手机号(如:138\*\*\*\*1234)
- ✅ **一键登录** - 获取华为账号授权码,支持后端验证登录
- ✅ **协议校验** - 完善的用户协议同意流程
- ✅ **错误处理** - 友好的错误提示和异常处理机制
### 📱 应用版本管理
- ✅ **版本检查** - 检查应用是否有新版本可用
- ✅ **更新对话框** - 显示系统原生更新对话框
- ✅ **自动更新** - 一键式自动检查并提示更新
- ✅ **版本信息** - 获取当前应用版本号和版本名称
- ✅ **Promise & 回调** - 支持 Promise 和回调两种调用方式
### 📨 推送服务集成
- ✅ **推送初始化** - 初始化华为推送服务(Push Kit)
- ✅ **推送Token** - 获取推送Token用于服务端推送
- ✅ **消息监听** - 监听前台和后台推送消息
- ✅ **权限请求** - 自动请求推送通知权限
- ✅ **消息处理** - 统一的推送消息处理机制
### 🔄 屏幕方向控制
- ✅ **设置方向** - 支持竖屏、横屏、自动旋转等
- ✅ **获取方向** - 获取当前屏幕方向
- ✅ **锁定方向** - 锁定当前屏幕方向
- ✅ **重置方向** - 快速重置为默认竖屏
### 系统服务跳转
- ✅ **系统设置** - 跳转到系统设置页面(首页、账号、应用详情等)
- ✅ **应用商城** - 跳转到应用市场评论页面
---
## 📋 目录结构
uni_modules/harmony-auth/ ├── utssdk/ │ ├── app-harmony/ │ │ ├── index.uts # 主入口文件(账号认证、屏幕控制、系统跳转) │ │ ├── button.ets # 原生登录按钮组件 │ │ ├── updateManager.uts # 版本更新管理模块 │ │ └── push.uts # 推送服务模块 │ ├── interface.uts # TypeScript 类型定义 │ └── unierror.uts # 错误码定义 ├── readme.md # 📖 使用文档(本文件) ├── changelog.md # 📝 更新日志 └── package.json # 插件配置
---
## 快速开始
### 1. 导入插件
```javascript
// 推荐方式:ES6 导入
import { getQuickLoginAnonymousPhone, getAuthorizationCode } from '@/uni_modules/harmony-auth';
// 或使用工具类封装
import HarmonyLoginUtil from '@/utils/harmonyLoginUtil.js';
📖 API 文档
一、华为账号认证
1.1 获取匿名手机号
获取华为账号绑定的脱敏手机号,用于登录页面展示。
函数签名:
getQuickLoginAnonymousPhone(): Promise<string>
返回值:
Promise<string>- 返回匿名手机号(如:138****1234),失败返回空字符串
使用示例:
import { getQuickLoginAnonymousPhone } from '@/uni_modules/harmony-auth';
// 方式一:async/await(推荐)
async function loadPhoneNumber() {
try {
const phone = await getQuickLoginAnonymousPhone();
if (phone) {
console.log('匿名手机号:', phone); // 138****1234
// 显示在登录按钮上
this.displayPhone = phone;
} else {
console.log('未获取到手机号');
}
} catch (error) {
console.error('获取手机号失败:', error);
}
}
// 方式二:Promise
getQuickLoginAnonymousPhone()
.then(phone => {
console.log('匿名手机号:', phone);
})
.catch(error => {
console.error('获取失败:', error);
});
注意事项:
- 用户必须在设备上登录华为账号
- 首次调用需要用户授权
- 返回的是脱敏后的手机号,不能用于实际通信
1.2 获取匿名手机号(回调方式)
兼容旧版的回调方式接口。
函数签名:
getAnonymousPhone(options: GetPhoneOptions): void
interface GetPhoneOptions {
success?: (res: PhoneSuccessResult) => void;
fail?: (err: AuthErrorResult) => void;
complete?: () => void;
}
使用示例:
import { getAnonymousPhone } from '@/uni_modules/harmony-auth';
getAnonymousPhone({
success: (res) => {
console.log('匿名手机号:', res.anonymousPhone);
},
fail: (err) => {
console.error('获取失败:', err.errMsg);
},
complete: () => {
console.log('请求完成');
}
});
二、应用版本管理
2.1 检查应用更新
检查应用是否有新版本可用。
函数签名:
checkAppUpdate(options?: VersionCheckOptions): void
interface VersionCheckOptions {
success?: (hasUpdate: boolean, checkResult?: CheckUpdateResult) => void;
fail?: (error: BusinessError) => void;
complete?: () => void;
autoShowDialog?: boolean; // 是否自动显示更新对话框
}
使用示例:
import { checkAppUpdate } from '@/uni_modules/harmony-auth';
// 基本用法
checkAppUpdate({
success: (hasUpdate, checkResult) => {
if (hasUpdate) {
console.log('有新版本可用');
console.log('检查结果:', checkResult);
} else {
console.log('已是最新版本');
}
},
fail: (error) => {
console.error('检查失败:', error.message);
}
});
// 自动显示更新对话框
checkAppUpdate({
autoShowDialog: true,
success: (hasUpdate) => {
console.log('更新检查完成:', hasUpdate);
}
});
2.2 显示更新对话框
显示系统原生的更新对话框。
函数签名:
showUpdateDialog(options?: ShowUpdateDialogOptions): void
使用示例:
import { showUpdateDialog } from '@/uni_modules/harmony-auth';
showUpdateDialog({
success: (resultCode) => {
console.log('对话框显示成功:', resultCode);
},
fail: (error) => {
console.error('对话框显示失败:', error.message);
}
});
2.3 自动检查更新(推荐)
一键式自动检查更新,如果有更新则显示对话框。适合在应用启动时调用。
函数签名:
autoCheckUpdate(options?: AutoCheckOptions): void
使用示例:
import { autoCheckUpdate } from '@/uni_modules/harmony-auth';
// 在 App.vue 的 onLaunch 中调用
export default {
onLaunch() {
// 自动检查更新
autoCheckUpdate({
success: (hasUpdate) => {
if (hasUpdate) {
console.log('发现新版本并已显示更新对话框');
}
}
});
}
}
2.4 Promise 方式 API
支持 async/await 的 Promise 方式。
使用示例:
import { checkAppUpdateAsync, showUpdateDialogAsync } from '@/uni_modules/harmony-auth';
// 检查更新
async function checkUpdate() {
try {
const { hasUpdate, checkResult } = await checkAppUpdateAsync();
if (hasUpdate) {
console.log('有新版本');
// 显示更新对话框
await showUpdateDialogAsync();
} else {
uni.showToast({ title: '已是最新版本', icon: 'none' });
}
} catch (error) {
console.error('检查更新失败:', error);
}
}
2.5 获取当前应用版本
获取当前应用的版本信息。
函数签名:
getCurrentAppVersion(): Promise<VersionInfo>
interface VersionInfo {
versionCode: number; // 版本号
versionName: string; // 版本名称
}
使用示例:
import { getCurrentAppVersion } from '@/uni_modules/harmony-auth';
async function getVersion() {
try {
const version = await getCurrentAppVersion();
console.log('当前版本:', version.versionName);
console.log('版本号:', version.versionCode);
} catch (error) {
console.error('获取版本失败:', error);
}
}
三、推送服务
3.1 初始化推送服务
初始化华为推送服务,请求推送权限。
函数签名:
initHarmonyPush(): Promise<boolean>
使用示例:
import { initHarmonyPush } from '@/uni_modules/harmony-auth';
// 在 App.vue 中初始化
export default {
async onLaunch() {
const success = await initHarmonyPush();
if (success) {
console.log('推送服务初始化成功');
} else {
console.log('推送服务初始化失败');
}
}
}
3.2 获取推送 Token
获取推送 Token,用于服务端推送消息。
函数签名:
getPushToken(): Promise<string>
使用示例:
import { getPushToken } from '@/uni_modules/harmony-auth';
async function getToken() {
try {
const token = await getPushToken();
console.log('推送Token:', token);
// 将 token 上传到服务器
await uploadTokenToServer(token);
} catch (error) {
console.error('获取Token失败:', error);
}
}
3.3 监听推送消息
注册推送消息回调函数。
函数签名:
onPushMessage(callback: (message: string) => void): void
offPushMessage(): void // 取消监听
使用示例:
import { onPushMessage, offPushMessage } from '@/uni_modules/harmony-auth';
// 注册监听
onPushMessage((message) => {
console.log('收到推送消息:', message);
try {
const data = JSON.parse(message);
// 处理推送消息
handlePushData(data);
} catch (error) {
console.error('解析推送消息失败:', error);
}
});
// 取消监听
onUnload(() => {
offPushMessage();
});
3.4 接收推送消息(供原生调用)
此函数由 EntryAbility 中的原生代码调用,用于接收推送消息并转发到 UTS 层。
函数签名:
receivePushMessage(payload: ESObject): void
在 EntryAbility 中的使用:
// EntryAbility.ets
import { receivePushMessage } from '@/uni_modules/harmony-auth';
import { pushService, pushCommon } from '@kit.PushKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 注册后台推送监听
pushService.receiveMessage(pushCommon.PushType.BACKGROUND, this, (data) => {
const payload = {
type: 'BACKGROUND',
data: data.data || null,
timestamp: Date.now()
};
receivePushMessage(payload);
});
// 注册前台推送监听
pushService.receiveMessage(pushCommon.PushType.FOREGROUND, this, (data) => {
const payload = {
type: 'FOREGROUND',
data: data.data || null,
timestamp: Date.now()
};
receivePushMessage(payload);
});
}
}
四、屏幕方向控制
4.1 设置屏幕方向
设置应用的屏幕方向。
函数签名:
setScreenOrientation(orientation: string): Promise<boolean>
// orientation 可选值:
// 'portrait' - 竖屏
// 'landscape' - 横屏
// 'auto' - 自动旋转
// 'portrait_inverted' - 反向竖屏
// 'landscape_inverted' - 反向横屏
使用示例:
import { setScreenOrientation } from '@/uni_modules/harmony-auth';
// 设置为横屏
async function setLandscape() {
const success = await setScreenOrientation('landscape');
if (success) {
console.log('已切换到横屏');
}
}
// 设置为竖屏
await setScreenOrientation('portrait');
// 自动旋转
await setScreenOrientation('auto');
4.2 获取当前屏幕方向
获取当前应用的屏幕方向。
函数签名:
getScreenOrientation(): Promise<string>
使用示例:
import { getScreenOrientation } from '@/uni_modules/harmony-auth';
const orientation = await getScreenOrientation();
console.log('当前方向:', orientation); // 'portrait' 或 'landscape'
4.3 锁定当前方向
锁定应用的当前屏幕方向。
函数签名:
lockOrientation(): Promise<boolean>
使用示例:
import { lockOrientation } from '@/uni_modules/harmony-auth';
// 锁定当前方向
await lockOrientation();
4.4 重置为默认方向
重置为默认竖屏方向。
函数签名:
resetOrientation(): Promise<boolean>
使用示例:
import { resetOrientation } from '@/uni_modules/harmony-auth';
// 重置为竖屏
await resetOrientation();
五、系统服务跳转
5.1 打开系统设置
跳转到系统设置页面。
函数签名:
openSystemSettings(type?: string): Promise<boolean>
// type 可选值:
// 'main' - 系统设置首页(默认)
// 'account' - 华为账号设置
// 'app' - 应用详情设置
// 'wifi' - WiFi 设置
// 'bluetooth' - 蓝牙设置
使用示例:
import { openSystemSettings } from '@/uni_modules/harmony-auth';
// 打开系统设置首页
await openSystemSettings();
// 打开华为账号设置
await openSystemSettings('account');
// 打开应用详情设置
await openSystemSettings('app');
5.2 打开应用商城评论页
跳转到应用市场的评论页面。
函数签名:
openAppGalleryReview(bundleName?: string): Promise<boolean>
使用示例:
import { openAppGalleryReview } from '@/uni_modules/harmony-auth';
// 跳转到当前应用的评论页
await openAppGalleryReview();
// 跳转到指定应用的评论页
await openAppGalleryReview('com.example.app');
💡 完整使用示例
示例 1:登录页面集成
Vue 页面示例(login.vue):
<template>
<view>
<!-- 显示匿名手机号 -->
<view v-if="quickLoginAnonymousPhone">
{{ quickLoginAnonymousPhone }}
</view>
<!-- 华为一键登录按钮 -->
<harmonyButton
:checked="agreementVal"
:triggerLogin="triggerHarmonyLogin"
:enableNetworkCheck="false"
@harmonyLogin="handleHarmonyLogin"
/>
<!-- 协议组件 -->
<agree
v-model="agreementVal"
ref="agreeRef"
@confirm="handleAgreeConfirm"
/>
</view>
</template>
<script setup>
import harmonyButton from "./components/harmonyButton.vue";
import agree from "./components/agree.vue";
import HarmonyLoginUtil from "@/utils/harmonyLoginUtil.js";
import useUserStore from "@/stores/user.js";
const quickLoginAnonymousPhone = ref("");
const agreementVal = ref(false);
const agreeRef = ref(null);
const triggerHarmonyLogin = ref(false);
const isLoggingIn = ref(false);
// 页面加载时获取匿名手机号
onLoad(() => {
loadHarmonyPhoneNumber();
});
const loadHarmonyPhoneNumber = async () => {
const phone = await HarmonyLoginUtil.getAnonymousPhone();
if (phone) {
quickLoginAnonymousPhone.value = phone;
}
};
// 用户同意协议后触发登录
const handleAgreeConfirm = () => {
isLoggingIn.value = true;
triggerHarmonyLogin.value = true;
setTimeout(() => {
triggerHarmonyLogin.value = false;
}, 1000);
};
// 处理登录结果
const handleHarmonyLogin = async (result) => {
if (result.needAgreement) {
agreeRef.value.openPopup();
return;
}
if (result.success && result.authCode) {
// 调用后端 API
await useUserStore().harmonyOneTouchLogin(result.authCode);
uni.switchTab({ url: '/pages/index/index' });
} else {
uni.showToast({
title: result.error || '登录失败',
icon: 'none'
});
}
isLoggingIn.value = false;
};
</script>
示例 2:版本更新集成
在 App.vue 中自动检查更新:
<script>
import { autoCheckUpdate, getCurrentAppVersion } from '@/uni_modules/harmony-auth';
export default {
onLaunch() {
// 显示当前版本信息
this.showCurrentVersion();
// 自动检查更新
this.checkForUpdates();
},
methods: {
async showCurrentVersion() {
try {
const version = await getCurrentAppVersion();
console.log(`当前版本: ${version.versionName} (${version.versionCode})`);
} catch (error) {
console.error('获取版本信息失败:', error);
}
},
checkForUpdates() {
autoCheckUpdate({
success: (hasUpdate) => {
if (hasUpdate) {
console.log('发现新版本');
// 已自动显示更新对话框
} else {
console.log('当前已是最新版本');
}
},
fail: (error) => {
console.error('检查更新失败:', error.message);
}
});
}
}
}
</script>
手动检查更新按钮:
<template>
<view>
<button @click="manualCheckUpdate">检查更新</button>
</view>
</template>
<script setup>
import { checkAppUpdateAsync, showUpdateDialogAsync } from '@/uni_modules/harmony-auth';
const manualCheckUpdate = async () => {
uni.showLoading({ title: '检查中...', mask: true });
try {
const { hasUpdate } = await checkAppUpdateAsync();
uni.hideLoading();
if (hasUpdate) {
// 显示更新对话框
await showUpdateDialogAsync();
} else {
uni.showToast({
title: '已是最新版本',
icon: 'success'
});
}
} catch (error) {
uni.hideLoading();
uni.showToast({
title: '检查更新失败',
icon: 'none'
});
}
};
</script>
示例 3:推送服务集成
在 App.vue 中初始化推送:
<script>
import {
initHarmonyPush,
getPushToken,
onPushMessage
} from '@/uni_modules/harmony-auth';
export default {
async onLaunch() {
// 初始化推送服务
await this.initPush();
// 注册推送消息监听
this.registerPushListener();
},
methods: {
async initPush() {
try {
// 初始化推送
const success = await initHarmonyPush();
if (!success) {
console.error('推送初始化失败');
return;
}
// 获取推送 Token
const token = await getPushToken();
if (token) {
console.log('推送Token:', token);
// 上传 Token 到服务器
await this.uploadPushToken(token);
}
} catch (error) {
console.error('推送初始化异常:', error);
}
},
registerPushListener() {
onPushMessage((message) => {
console.log('收到推送消息:', message);
try {
const data = JSON.parse(message);
this.handlePushMessage(data);
} catch (error) {
console.error('解析推送消息失败:', error);
}
});
},
handlePushMessage(data) {
// 根据不同的 action 处理推送
switch (data.action) {
case 'updateStudentInfo':
// 更新学生信息
this.refreshStudentInfo();
break;
case 'newMessage':
// 显示新消息提示
uni.showToast({
title: data.content || '您有新消息',
icon: 'none'
});
break;
default:
console.log('未知推送类型:', data.action);
}
},
async uploadPushToken(token) {
// 上传 Token 到您的服务器
try {
await uni.request({
url: 'https://your-api.com/push/token',
method: 'POST',
data: { token }
});
} catch (error) {
console.error('上传Token失败:', error);
}
}
}
}
</script>
示例 4:屏幕方向控制
视频播放器场景:
<template>
<view>
<video
:src="videoUrl"
@fullscreenchange=""
/>
</view>
</template>
<script setup>
import {
setScreenOrientation,
resetOrientation
} from '@/uni_modules/harmony-auth';
// 全屏时切换到横屏
const = async (e) => {
if (e.detail.fullScreen) {
// 进入全屏,切换到横屏
await setScreenOrientation('landscape');
} else {
// 退出全屏,恢复竖屏
await resetOrientation();
}
};
// 页面卸载时恢复竖屏
onUnmount(async () => {
await resetOrientation();
});
</script>
📚 类型定义
华为账号认证相关
// 授权选项
interface AuthOptions {
bundleName?: string;
forceLogin?: boolean;
success?: (res: AuthSuccessResult) => void;
fail?: (err: AuthErrorResult) => void;
complete?: () => void;
}
// 获取手机号选项
interface GetPhoneOptions {
success?: (res: PhoneSuccessResult) => void;
fail?: (err: AuthErrorResult) => void;
complete?: () => void;
}
// 授权成功结果
interface AuthSuccessResult {
code: string; // 授权码
authCode: string; // 授权码(兼容字段)
state?: string;
errCode: number;
errMsg: string;
}
// 授权失败结果
interface AuthErrorResult {
errCode: number;
errMsg: string;
}
// 手机号成功结果
interface PhoneSuccessResult {
anonymousPhone: string; // 匿名手机号
errCode: number;
errMsg: string;
}
版本更新相关
// 版本信息
interface VersionInfo {
versionCode: number; // 版本号
versionName: string; // 版本名称
}
// 版本检查选项
interface VersionCheckOptions {
success?: (hasUpdate: boolean, checkResult?: CheckUpdateResult) => void;
fail?: (error: BusinessError) => void;
complete?: () => void;
autoShowDialog?: boolean;
}
// 更新对话框选项
interface ShowUpdateDialogOptions {
success?: (resultCode: ShowUpdateResultCode) => void;
fail?: (error: BusinessError) => void;
complete?: () => void;
}
// 检查更新结果
interface CheckUpdateResult {
hasUpdate: boolean;
checkResult?: any;
}
⚠️ 错误码说明
华为账号认证错误码
| 错误码 | 含义 | 处理建议 |
|---|---|---|
1005300001 |
未同意协议 | 弹出协议弹窗,引导用户同意 |
1001502001 |
未登录华为账号 | 引导用户登录系统账号 |
1001502005 |
网络异常 | 检查网络连接,提示用户重试 |
1001502009 |
内部错误 | 提示用户稍后重试或使用其他登录方式 |
1001502012 |
用户取消授权 | 提示用户可使用其他登录方式 |
12300001 |
系统服务异常 | 提示用户稍后重试 |
1001500002 |
重复请求 | 已在处理中,无需额外操作 |
错误处理示例
import { ErrorCode, dealAllError } from '@/uni_modules/harmony-auth';
try {
// 执行登录操作
} catch (error) {
// 使用内置的错误处理函数
dealAllError(error);
// 或自定义错误处理
if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
uni.showModal({
title: '提示',
content: '请先登录华为账号',
confirmText: '去登录',
success: (res) => {
if (res.confirm) {
// 跳转到系统账号设置
openSystemSettings('account');
}
}
});
}
}
🔧 高级配置
1. 配置推送消息处理
在 EntryAbility.ets 中集成推送监听:
import { receivePushMessage } from '@/uni_modules/harmony-auth';
import { pushService, pushCommon } from '@kit.PushKit';
import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'EntryAbility', 'onCreate');
// 注册后台推送消息监听
pushService.receiveMessage(
pushCommon.PushType.BACKGROUND,
this,
(data: pushCommon.PushPayload) => {
const payload = {
type: 'BACKGROUND',
data: data.data || null,
timestamp: Date.now()
};
receivePushMessage(payload);
}
);
// 注册前台推送消息监听
pushService.receiveMessage(
pushCommon.PushType.FOREGROUND,
this,
(data: pushCommon.PushPayload) => {
const payload = {
type: 'FOREGROUND',
data: data.data || null,
timestamp: Date.now()
};
receivePushMessage(payload);
}
);
}
}
2. 配置屏幕方向
在 module.json5 中配置默认方向:
{
"module": {
"abilities": [
{
"name": "EntryAbility",
"orientation": "portrait" // 默认竖屏
}
]
}
}
🎯 最佳实践
1. 协议校验流程
// ❌ 错误做法:未同意协议直接登录
const handleLogin = async () => {
const code = await getAuthCode();
await login(code);
};
// ✅ 正确做法:先检查协议
const handleLogin = async () => {
if (!agreementChecked.value) {
// 显示协议弹窗
showAgreementDialog();
return;
}
const code = await getAuthCode();
await login(code);
};
2. 防重复登录
// 使用标志位防止重复登录
const isLoggingIn = ref(false);
const handleLogin = async () => {
if (isLoggingIn.value) {
console.log('登录中,请勿重复操作');
return;
}
isLoggingIn.value = true;
try {
await doLogin();
} finally {
isLoggingIn.value = false;
}
};
3. 版本更新时机
// 推荐在应用启动时静默检查
export default {
onLaunch() {
// 延迟 1 秒检查,避免影响启动性能
setTimeout(() => {
autoCheckUpdate();
}, 1000);
}
}
// 也可以在"关于"页面提供手动检查
const checkUpdate = async () => {
const { hasUpdate } = await checkAppUpdateAsync();
if (!hasUpdate) {
uni.showToast({ title: '已是最新版本', icon: 'none' });
}
};
4. 推送消息处理
// 统一的推送消息处理器
class PushMessageHandler {
constructor() {
this.handlers = new Map();
}
// 注册消息处理器
register(action, handler) {
this.handlers.set(action, handler);
}
// 处理推送消息
handle(message) {
try {
const data = JSON.parse(message);
const handler = this.handlers.get(data.action);
if (handler) {
handler(data);
} else {
console.log('未注册的推送类型:', data.action);
}
} catch (error) {
console.error('推送消息处理失败:', error);
}
}
}
// 使用示例
const pushHandler = new PushMessageHandler();
pushHandler.register('updateStudentInfo', (data) => {
// 更新学生信息
});
pushHandler.register('newMessage', (data) => {
// 显示新消息
});
onPushMessage((message) => {
pushHandler.handle(message);
});
🐛 常见问题
Q1: 获取不到匿名手机号?
原因:
- 用户未登录华为账号
- 应用指纹配置不正确
- 未在华为开发者后台启用账号服务
解决方案:
- 检查设备是否登录华为账号
- 验证应用包名和签名指纹是否正确配置
- 确认华为开发者后台已启用 Account Kit
Q2: 登录时提示未同意协议?
原因:
- 用户未勾选同意用户协议
解决方案:
// 先检查协议状态
if (!isAgreed.value) {
showAgreementDialog();
return;
}
Q3: 版本更新检查失败?
原因:
- 应用未上架华为应用市场
- 网络连接问题
- 未配置正确的包名
解决方案:
- 确保应用已上架华为应用市场
- 检查网络连接
- 验证 bundleName 配置
Q4: 推送权限请求失败?
原因:
- 用户拒绝权限
- 其他对话框正在显示(错误码 1600013)
解决方案:
// 插件已内置重试机制
// 如果用户拒绝,引导用户到设置页开启
if (error.code === 201) {
uni.showModal({
title: '需要通知权限',
content: '请在设置中开启通知权限',
confirmText: '去设置',
success: (res) => {
if (res.confirm) {
openSystemSettings('app');
}
}
});
}
Q5: 屏幕方向切换不生效?
原因:
- 系统已锁定屏幕方向
- module.json5 中配置了固定方向
解决方案:
- 检查系统设置中的自动旋转开关
- 确认 module.json5 中的 orientation 配置
📄 开源协议
MIT License
🔗 相关链接
- HarmonyOS Account Kit 官方文档
- HarmonyOS Push Kit 官方文档
- HarmonyOS Store Kit 官方文档
- uni-app-x UTS 插件开发指南
- 华为开发者联盟
📞 技术支持
如有问题或建议,欢迎:
- 提交 Issue
- 发送邮件至开发者
- 加入技术交流群:***
版本: 1.0.0
最后更新: 2025-12-13
作者: harmony-auth 团队

收藏人数:
下载插件并导入HBuilderX
赞赏(0)
下载 7
赞赏 0
下载 13127406
赞赏 1843
赞赏
京公网安备:11010802035340号