WiFi热点:HarmonyOS APP开发创建与配置热点
WiFi热点:HarmonyOS APP开发创建与配置热点
有时候,我们需要让手机变成一个"路由器"——比如多台设备间快速传输数据、为其他设备提供临时网络、或者实现设备间的直接通信。这就是WiFi热点(Hotspot)的用武之地。今天咱们就来聊聊鸿蒙系统中WiFi热点的创建与配置,看看如何让你的应用具备"开热点"的能力。
一、背景与动机
1.1 WiFi热点的应用场景
WiFi热点功能在实际开发中有着广泛的应用:
场景一:智能设备配网
很多智能家居设备(如智能灯泡、摄像头)没有屏幕和输入设备,无法直接输入WiFi密码。通过让手机创建热点,设备连接后获取配网信息,再切换到家庭WiFi,这就是经典的"热点配网"模式。
场景二:设备间数据传输
当两台设备需要快速传输大文件时,通过WiFi热点建立连接,速度远超蓝牙。很多"一键换机"应用就是利用这个原理。
场景三:网络共享
在没有路由器的场景下,将移动数据共享给其他设备使用,这是最常见的热点用途。
1.2 鸿蒙热点管理架构
鸿蒙系统提供了完整的WiFi热点API,支持灵活配置:
| 功能模块 | 说明 | 关键API |
|---|---|---|
| 热点开关 | 开启/关闭热点 | enableHotspot, disableHotspot |
| 配置管理 | 设置SSID、密码等 | setHotspotConfig, getHotspotConfig |
| 连接管理 | 查看连接设备 | getHotspotStations |
| 状态监听 | 热点状态变化 | on(‘hotspotStateChange’) |
二、核心原理
2.1 热点工作流程
创建一个WiFi热点看似简单,实则涉及多个系统层面的操作:

2.2 热点配置参数详解
创建热点时需要配置多个参数,每个参数都影响着热点的可用性和性能:
interface HotspotConfig {
// 热点名称(SSID)
ssid: string;
// 热点密码
preSharedKey: string;
// 安全类型
securityType: HotspotSecurityType;
// 频段:2.4GHz或5GHz
band: HotspotBandType;
// 信道(可选,自动选择则不设置)
channel?: number;
// 最大连接数
maxStationCount?: number;
// 是否隐藏SSID
hiddenSsid?: boolean;
}
参数说明:
| 参数 | 说明 | 推荐值 |
|---|---|---|
| ssid | 热点名称,建议使用英文避免兼容问题 | App名称或设备名 |
| preSharedKey | 密码,至少8位 | 随机生成8位以上 |
| securityType | 安全类型 | WPA2_PSK(最兼容) |
| band | 频段 | 2.4GHz(兼容性好) |
| maxStationCount | 最大连接数 | 8-10个 |
2.3 热点状态流转
理解热点的状态变化对于正确处理业务逻辑至关重要:

三、代码实战
3.1 热点管理核心类封装
先来封装一个完整的热点管理工具类:
import wifiManager from '@ohos.wifiManager';
import { BusinessError } from '@ohos.base';
/**
* WiFi热点管理器
* 封装热点创建、配置、状态监听等核心功能
*/
export class WifiHotspotManager {
private static instance: WifiHotspotManager;
private hotspotConfig: wifiManager.HotspotConfig | null = null;
private stateChangeCallback: ((state: number) => void) | null = null;
private stationJoinCallback: ((station: wifiManager.StationInfo) => void) | null = null;
private stationLeaveCallback: ((station: wifiManager.StationInfo) => void) | null = null;
private constructor() {
this.initEventListeners();
}
/**
* 获取单例实例
*/
public static getInstance(): WifiHotspotManager {
if (!WifiHotspotManager.instance) {
WifiHotspotManager.instance = new WifiHotspotManager();
}
return WifiHotspotManager.instance;
}
/**
* 初始化事件监听
*/
private initEventListeners(): void {
// 监听热点状态变化
wifiManager.on('hotspotStateChange', (state: number) => {
const stateText = state === 1 ? '已开启' : '已关闭';
console.info(`[热点] 状态变化: ${stateText}`);
if (this.stateChangeCallback) {
this.stateChangeCallback(state);
}
});
// 监听设备连接
wifiManager.on('hotspotStaJoin', (station: wifiManager.StationInfo) => {
console.info(`[热点] 设备连接: ${station.deviceAddress}`);
if (this.stationJoinCallback) {
this.stationJoinCallback(station);
}
});
// 监听设备断开
wifiManager.on('hotspotStaLeave', (station: wifiManager.StationInfo) => {
console.info(`[热点] 设备断开: ${station.deviceAddress}`);
if (this.stationLeaveCallback) {
this.stationLeaveCallback(station);
}
});
}
/**
* 检查热点是否已开启
*/
public async isHotspotEnabled(): Promise<boolean> {
try {
const isActive = wifiManager.isHotspotActive();
console.info(`[热点] 当前状态: ${isActive ? '已开启' : '未开启'}`);
return isActive;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 检查状态失败: ${err.message}`);
return false;
}
}
/**
* 创建并开启热点
* @param ssid 热点名称
* @param password 热点密码
* @param band 频段类型
*/
public async createHotspot(
ssid: string,
password: string,
band: wifiManager.HotspotBandType = wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G
): Promise<boolean> {
try {
// 检查是否已开启
const isEnabled = await this.isHotspotEnabled();
if (isEnabled) {
console.info('[热点] 热点已开启,先关闭');
await wifiManager.disableHotspot();
}
// 构建热点配置
this.hotspotConfig = {
ssid: ssid,
securityType: wifiManager.HotspotSecurityType.WIFI_SEC_TYPE_PSK,
band: band,
preSharedKey: password,
maxStationCount: 8
};
// 设置热点配置
await wifiManager.setHotspotConfig(this.hotspotConfig);
console.info(`[热点] 配置已设置: ${ssid}`);
// 开启热点
await wifiManager.enableHotspot();
console.info('[热点] 开启成功');
return true;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 创建失败: ${err.message}`);
return false;
}
}
/**
* 创建开放热点(无密码)
* 注意:开放热点存在安全风险,谨慎使用
*/
public async createOpenHotspot(
ssid: string,
band: wifiManager.HotspotBandType = wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G
): Promise<boolean> {
try {
const isEnabled = await this.isHotspotEnabled();
if (isEnabled) {
await wifiManager.disableHotspot();
}
this.hotspotConfig = {
ssid: ssid,
securityType: wifiManager.HotspotSecurityType.WIFI_SEC_TYPE_OPEN,
band: band,
maxStationCount: 8
};
await wifiManager.setHotspotConfig(this.hotspotConfig);
await wifiManager.enableHotspot();
console.info('[热点] 开放热点开启成功');
return true;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 创建开放热点失败: ${err.message}`);
return false;
}
}
/**
* 关闭热点
*/
public async closeHotspot(): Promise<boolean> {
try {
await wifiManager.disableHotspot();
console.info('[热点] 已关闭');
return true;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 关闭失败: ${err.message}`);
return false;
}
}
/**
* 获取当前热点配置
*/
public async getHotspotConfig(): Promise<wifiManager.HotspotConfig | null> {
try {
const config = await wifiManager.getHotspotConfig();
console.info(`[热点] 当前配置: ${config.ssid}`);
return config;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 获取配置失败: ${err.message}`);
return null;
}
}
/**
* 获取已连接的设备列表
*/
public async getConnectedStations(): Promise<Array<wifiManager.StationInfo>> {
try {
const stations = await wifiManager.getHotspotStations();
console.info(`[热点] 已连接 ${stations.length} 台设备`);
return stations;
} catch (error) {
const err = error as BusinessError;
console.error(`[热点] 获取设备列表失败: ${err.message}`);
return [];
}
}
/**
* 设置状态变化回调
*/
public setStateChangeCallback(callback: (state: number) => void): void {
this.stateChangeCallback = callback;
}
/**
* 设置设备连接回调
*/
public setStationJoinCallback(callback: (station: wifiManager.StationInfo) => void): void {
this.stationJoinCallback = callback;
}
/**
* 设置设备断开回调
*/
public setStationLeaveCallback(callback: (station: wifiManager.StationInfo) => void): void {
this.stationLeaveCallback = callback;
}
/**
* 移除所有监听
*/
public removeAllListeners(): void {
wifiManager.off('hotspotStateChange');
wifiManager.off('hotspotStaJoin');
wifiManager.off('hotspotStaLeave');
console.info('[热点] 已移除所有监听');
}
/**
* 生成随机密码
* @param length 密码长度,默认8位
*/
public generateRandomPassword(length: number = 8): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let password = '';
for (let i = 0; i < length; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
return password;
}
}
3.2 热点管理UI实现
接下来实现一个完整的热点管理页面:
import { WifiHotspotManager } from './WifiHotspotManager';
import wifiManager from '@ohos.wifiManager';
@Entry
@Component
struct HotspotManagePage {
// 热点管理器实例
private hotspotManager: WifiHotspotManager = WifiHotspotManager.getInstance();
// 状态变量
@State hotspotEnabled: boolean = false;
@State ssid: string = 'MyHotspot';
@State password: string = '';
@State band: wifiManager.HotspotBandType = wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G;
@State connectedDevices: Array<wifiManager.StationInfo> = [];
@State isCreating: boolean = false;
aboutToAppear(): void {
this.initState();
this.registerCallbacks();
}
aboutToDisappear(): void {
this.hotspotManager.removeAllListeners();
}
/**
* 初始化状态
*/
async initState(): Promise<void> {
this.hotspotEnabled = await this.hotspotManager.isHotspotEnabled();
if (this.hotspotEnabled) {
const config = await this.hotspotManager.getHotspotConfig();
if (config) {
this.ssid = config.ssid;
this.password = config.preSharedKey || '';
this.band = config.band;
}
this.connectedDevices = await this.hotspotManager.getConnectedStations();
}
}
/**
* 注册回调
*/
registerCallbacks(): void {
// 状态变化回调
this.hotspotManager.setStateChangeCallback((state: number) => {
this.hotspotEnabled = state === 1;
if (this.hotspotEnabled) {
this.refreshConnectedDevices();
} else {
this.connectedDevices = [];
}
});
// 设备连接回调
this.hotspotManager.setStationJoinCallback((station: wifiManager.StationInfo) => {
this.refreshConnectedDevices();
});
// 设备断开回调
this.hotspotManager.setStationLeaveCallback((station: wifiManager.StationInfo) => {
this.refreshConnectedDevices();
});
}
/**
* 刷新已连接设备列表
*/
async refreshConnectedDevices(): Promise<void> {
this.connectedDevices = await this.hotspotManager.getConnectedStations();
}
/**
* 创建热点
*/
async createHotspot(): Promise<void> {
if (!this.ssid) {
console.warn('[UI] 请输入热点名称');
return;
}
if (!this.password || this.password.length < 8) {
console.warn('[UI] 密码至少8位');
return;
}
this.isCreating = true;
const success = await this.hotspotManager.createHotspot(
this.ssid,
this.password,
this.band
);
this.isCreating = false;
if (success) {
this.hotspotEnabled = true;
}
}
/**
* 关闭热点
*/
async closeHotspot(): Promise<void> {
const success = await this.hotspotManager.closeHotspot();
if (success) {
this.hotspotEnabled = false;
this.connectedDevices = [];
}
}
/**
* 生成随机密码
*/
generatePassword(): void {
this.password = this.hotspotManager.generateRandomPassword(8);
}
build() {
Column() {
// 标题栏
Row() {
Text('WiFi热点')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor('#FFFFFF')
Blank()
// 状态指示
Row() {
Circle()
.width(10)
.height(10)
.fill(this.hotspotEnabled ? '#4CAF50' : '#666666')
Text(this.hotspotEnabled ? '已开启' : '未开启')
.fontSize(14)
.fontColor('#AAAAAA')
.margin({ left: 8 })
}
}
.width('100%')
.padding(20)
.backgroundColor('#1A1A2E')
// 配置区域
Column() {
// SSID输入
Column() {
Text('热点名称')
.fontSize(14)
.fontColor('#AAAAAA')
.width('100%')
TextInput({ text: $$this.ssid, placeholder: '请输入热点名称' })
.width('100%')
.height(50)
.backgroundColor('#16213E')
.fontColor('#FFFFFF')
.margin({ top: 8 })
.enabled(!this.hotspotEnabled)
}
.width('100%')
.alignItems(HorizontalAlign.Start)
.margin({ bottom: 20 })
// 密码输入
Column() {
Row() {
Text('热点密码')
.fontSize(14)
.fontColor('#AAAAAA')
Blank()
Button('随机生成')
.fontSize(12)
.height(30)
.backgroundColor('#4A90E2')
.onClick(() => {
this.generatePassword();
})
.enabled(!this.hotspotEnabled)
}
.width('100%')
Row() {
TextInput({ text: $$this.password, placeholder: '请输入密码(至少8位)' })
.width('80%')
.height(50)
.type(InputType.Password)
.backgroundColor('#16213E')
.fontColor('#FFFFFF')
.margin({ top: 8 })
.enabled(!this.hotspotEnabled)
Text(`${this.password.length}/8`)
.fontSize(12)
.fontColor(this.password.length >= 8 ? '#4CAF50' : '#FF5722')
.margin({ left: 10 })
}
.width('100%')
}
.width('100%')
.alignItems(HorizontalAlign.Start)
.margin({ bottom: 20 })
// 频段选择
Column() {
Text('频段选择')
.fontSize(14)
.fontColor('#AAAAAA')
.width('100%')
Row() {
Button('2.4GHz')
.width('45%')
.height(40)
.backgroundColor(
this.band === wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G
? '#4A90E2' : '#333333'
)
.onClick(() => {
this.band = wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G;
})
.enabled(!this.hotspotEnabled)
Button('5GHz')
.width('45%')
.height(40)
.backgroundColor(
this.band === wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_5G
? '#4A90E2' : '#333333'
)
.onClick(() => {
this.band = wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_5G;
})
.enabled(!this.hotspotEnabled)
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.margin({ top: 10 })
}
.width('100%')
.alignItems(HorizontalAlign.Start)
.margin({ bottom: 30 })
// 操作按钮
if (this.hotspotEnabled) {
Button('关闭热点')
.width('100%')
.height(50)
.backgroundColor('#FF5722')
.onClick(() => {
this.closeHotspot();
})
} else {
Button(this.isCreating ? '创建中...' : '创建热点')
.width('100%')
.height(50)
.backgroundColor('#4A90E2')
.enabled(!this.isCreating)
.onClick(() => {
this.createHotspot();
})
}
}
.width('90%')
.padding(20)
.backgroundColor('#16213E')
.borderRadius(12)
.margin({ top: 20 })
// 已连接设备列表
if (this.hotspotEnabled && this.connectedDevices.length > 0) {
Column() {
Row() {
Text('已连接设备')
.fontSize(16)
.fontColor('#FFFFFF')
Blank()
Text(`${this.connectedDevices.length} 台`)
.fontSize(14)
.fontColor('#AAAAAA')
}
.width('100%')
.margin({ bottom: 15 })
ForEach(this.connectedDevices, (device: wifiManager.StationInfo, index: number) => {
Row() {
Text(`设备 ${index + 1}`)
.fontSize(14)
.fontColor('#FFFFFF')
Blank()
Text(device.deviceAddress)
.fontSize(12)
.fontColor('#AAAAAA')
}
.width('100%')
.padding({ top: 10, bottom: 10 })
.border({ width: { bottom: 1 }, color: '#333333' })
})
}
.width('90%')
.padding(20)
.backgroundColor('#16213E')
.borderRadius(12)
.margin({ top: 20 })
}
// 热点信息提示
if (this.hotspotEnabled) {
Column() {
Text('连接信息')
.fontSize(16)
.fontColor('#FFFFFF')
.width('100%')
.margin({ bottom: 15 })
Row() {
Text('热点名称:')
.fontSize(14)
.fontColor('#AAAAAA')
Text(this.ssid)
.fontSize(14)
.fontColor('#FFFFFF')
.margin({ left: 10 })
}
.width('100%')
.margin({ bottom: 10 })
Row() {
Text('密码:')
.fontSize(14)
.fontColor('#AAAAAA')
Text(this.password)
.fontSize(14)
.fontColor('#FFFFFF')
.margin({ left: 10 })
}
.width('100%')
}
.width('90%')
.padding(20)
.backgroundColor('#16213E')
.borderRadius(12)
.margin({ top: 20 })
}
}
.width('100%')
.height('100%')
.backgroundColor('#0F0F1A')
}
}
3.3 智能配网场景实现
热点最常见的应用场景之一就是智能设备配网。下面实现一个完整的配网流程:
import { WifiHotspotManager } from './WifiHotspotManager';
import wifiManager from '@ohos.wifiManager';
/**
* 智能设备配网管理器
* 通过热点实现设备配网
*/
export class SmartConfigManager {
private hotspotManager: WifiHotspotManager = WifiHotspotManager.getInstance();
private configServer: any = null; // 实际项目中需要实现Socket服务
private isConfiguring: boolean = false;
/**
* 开始配网流程
* @param targetWifiSsid 目标WiFi名称
* @param targetWifiPassword 目标WiFi密码
*/
public async startSmartConfig(
targetWifiSsid: string,
targetWifiPassword: string
): Promise<boolean> {
if (this.isConfiguring) {
console.warn('[配网] 配网进行中,请勿重复操作');
return false;
}
this.isConfiguring = true;
try {
// 步骤1:创建配网热点
const hotspotSsid = 'SmartConfig_' + Date.now().toString().slice(-6);
const hotspotPassword = this.hotspotManager.generateRandomPassword(8);
console.info(`[配网] 创建热点: ${hotspotSsid}`);
const hotspotCreated = await this.hotspotManager.createHotspot(
hotspotSsid,
hotspotPassword
);
if (!hotspotCreated) {
this.isConfiguring = false;
return false;
}
// 步骤2:等待设备连接热点
console.info('[配网] 等待设备连接...');
const deviceConnected = await this.waitForDeviceConnect(30000);
if (!deviceConnected) {
console.error('[配网] 设备连接超时');
await this.hotspotManager.closeHotspot();
this.isConfiguring = false;
return false;
}
// 步骤3:发送配网信息给设备
console.info('[配网] 发送配网信息');
const configSent = await this.sendConfigToDevice(
targetWifiSsid,
targetWifiPassword
);
// 步骤4:关闭热点
await this.hotspotManager.closeHotspot();
// 步骤5:连接到目标WiFi
if (configSent) {
console.info('[配网] 等待设备连接目标WiFi');
// 这里可以添加验证逻辑,等待设备上线
}
this.isConfiguring = false;
return configSent;
} catch (error) {
console.error('[配网] 配网异常:', error);
await this.hotspotManager.closeHotspot();
this.isConfiguring = false;
return false;
}
}
/**
* 等待设备连接热点
* @param timeout 超时时间(毫秒)
*/
private async waitForDeviceConnect(timeout: number): Promise<boolean> {
return new Promise((resolve) => {
let isResolved = false;
const timer = setTimeout(() => {
if (!isResolved) {
isResolved = true;
resolve(false);
}
}, timeout);
// 监听设备连接
this.hotspotManager.setStationJoinCallback((station: wifiManager.StationInfo) => {
if (!isResolved) {
console.info(`[配网] 设备已连接: ${station.deviceAddress}`);
isResolved = true;
clearTimeout(timer);
resolve(true);
}
});
});
}
/**
* 发送配网信息给设备
* 实际项目中需要通过Socket通信
*/
private async sendConfigToDevice(
ssid: string,
password: string
): Promise<boolean> {
// 构建配网数据包
const configData = {
type: 'wifi_config',
ssid: ssid,
password: password,
timestamp: Date.now()
};
console.info('[配网] 配网数据:', JSON.stringify(configData));
// 实际项目中需要:
// 1. 创建Socket服务
// 2. 等待设备连接
// 3. 发送配网数据
// 4. 接收设备确认
// 模拟发送成功
await this.delay(2000);
return true;
}
/**
* 延时函数
*/
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* 取消配网
*/
public async cancelConfig(): Promise<void> {
if (this.isConfiguring) {
await this.hotspotManager.closeHotspot();
this.isConfiguring = false;
console.info('[配网] 已取消');
}
}
}
配网流程图:
flowchart TD
A[用户触发配网] --> B[创建临时热点]
B --> C[显示热点信息]
C --> D[等待设备连接热点]
D --> E{设备是否连接?}
E -->|超时| F[配网失败]
E -->|已连接| G[建立Socket通信]
G --> H[发送WiFi凭据]
H --> I[设备接收配置]
I --> J[关闭临时热点]
J --> K[设备连接目标WiFi]
K --> L[验证设备上线]
L --> M{验证是否成功?}
M -->|成功| N[配网完成]
M -->|失败| O[提示重试]
classDef primary fill:#4A90E2,stroke:#2E5B8C,color:#fff
classDef warning fill:#F5A623,stroke:#C17A00,color:#fff
classDef error fill:#E74C3C,stroke:#C0392B,color:#fff
classDef success fill:#4CAF50,stroke:#388E3C,color:#fff
class A,N success
class B,C,D,G,H,I,J,K,L warning
class F,O error
class E,M primary
四、踩坑与注意事项
4.1 权限配置
坑点:热点功能需要特殊权限,容易被忽略。
// module.json5 完整权限配置
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.GET_WIFI_INFO",
"reason": "获取WiFi信息"
},
{
"name": "ohos.permission.SET_WIFI_INFO",
"reason": "修改WiFi设置"
},
{
"name": "ohos.permission.MANAGE_WIFI_HOTSPOT",
"reason": "管理WiFi热点"
},
{
"name": "ohos.permission.GET_WIFI_CONFIG",
"reason": "获取WiFi配置"
},
{
"name": "ohos.permission.SET_WIFI_CONFIG",
"reason": "修改WiFi配置"
}
]
}
}
4.2 热点与WiFi互斥
坑点:开启热点时,WiFi连接会被断开。
/**
* 安全切换到热点模式
* 先保存当前WiFi信息,再开启热点
*/
async function switchToHotspotMode(ssid: string, password: string): Promise<boolean> {
// 保存当前WiFi连接信息
let previousWifi: { ssid: string, connected: boolean } = { ssid: '', connected: false };
try {
const linkedInfo = await wifiManager.getLinkedInfo();
if (linkedInfo && linkedInfo.connState === wifiManager.WifiConnState.WIFI_CONNECTED) {
previousWifi = {
ssid: linkedInfo.ssid,
connected: true
};
console.info(`[切换] 保存当前WiFi: ${previousWifi.ssid}`);
}
} catch (error) {
console.warn('[切换] 获取当前WiFi失败');
}
// 开启热点(会自动断开WiFi)
const hotspotManager = WifiHotspotManager.getInstance();
const success = await hotspotManager.createHotspot(ssid, password);
if (success) {
// 保存previousWifi用于后续恢复
// 可以存储到Preferences中
}
return success;
}
4.3 频段兼容性
坑点:5GHz热点不是所有设备都支持。
/**
* 智能选择频段
* 根据设备能力选择最佳频段
*/
async function selectOptimalBand(): Promise<wifiManager.HotspotBandType> {
try {
// 检查是否支持5GHz
const supportedBands = await wifiManager.getSupportedBands();
const supports5G = supportedBands.includes(wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_5G);
if (supports5G) {
// 还需要考虑连接设备的兼容性
// 如果预期连接的是老设备,建议使用2.4GHz
console.info('[频段] 支持5GHz,使用5GHz频段');
return wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_5G;
} else {
console.info('[频段] 不支持5GHz,使用2.4GHz频段');
return wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G;
}
} catch (error) {
// 默认使用2.4GHz,兼容性最好
console.warn('[频段] 检测失败,使用2.4GHz');
return wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G;
}
}
4.4 连接数限制
坑点:不同设备支持的最大连接数不同。
/**
* 安全设置最大连接数
*/
async function safeSetMaxStationCount(count: number): Promise<number> {
try {
// 获取设备支持的最大连接数
const maxSupported = await wifiManager.getMaxSupportedStationCount();
// 取最小值
const actualCount = Math.min(count, maxSupported);
console.info(`[热点] 设置最大连接数: ${actualCount} (支持: ${maxSupported})`);
return actualCount;
} catch (error) {
// 默认值
return 8;
}
}
4.5 SSID编码问题
坑点:中文SSID可能导致部分设备无法识别。
/**
* 生成兼容性SSID
*/
function generateCompatibleSsid(prefix: string): string {
// 方案1:纯英文+数字
const timestamp = Date.now().toString().slice(-6);
const ssid = `${prefix}_${timestamp}`;
// 方案2:如果需要中文,确保编码正确
// const ssid = encodeURIComponent('我的热点');
// 验证SSID长度(最大32字节)
if (ssid.length > 32) {
return ssid.substring(0, 32);
}
return ssid;
}
五、HarmonyOS 6适配
5.1 API变更
HarmonyOS 6对热点API进行了增强:
| API | HarmonyOS 5 | HarmonyOS 6 | 说明 |
|---|---|---|---|
| setHotspotConfig() | 基础配置 | 支持更多参数 | 新增隐藏SSID、频段自动切换等 |
| getHotspotStations() | 返回设备地址 | 返回完整信息 | 包含设备名、信号强度等 |
| 新增API | - | setHotspotIdleTimeout() | 设置热点空闲超时 |
适配代码:
/**
* HarmonyOS 6热点配置适配
*/
async function createHotspotAdaptive(ssid: string, password: string): Promise<boolean> {
const apiVersion = getApiVersion();
try {
if (apiVersion >= 6) {
// HarmonyOS 6 新特性
const config: wifiManager.HotspotConfig = {
ssid: ssid,
preSharedKey: password,
securityType: wifiManager.HotspotSecurityType.WIFI_SEC_TYPE_PSK,
band: wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_AUTO, // 自动选择频段
maxStationCount: 10,
hiddenSsid: false,
// 新增参数
autoShutdown: true, // 无设备连接时自动关闭
idleTimeout: 300000 // 5分钟无连接自动关闭
};
await wifiManager.setHotspotConfig(config);
await wifiManager.enableHotspot();
return true;
} else {
// HarmonyOS 5 兼容写法
const config: wifiManager.HotspotConfig = {
ssid: ssid,
preSharedKey: password,
securityType: wifiManager.HotspotSecurityType.WIFI_SEC_TYPE_PSK,
band: wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_2G,
maxStationCount: 8
};
await wifiManager.setHotspotConfig(config);
await wifiManager.enableHotspot();
return true;
}
} catch (error) {
console.error('[热点] 创建失败:', error);
return false;
}
}
5.2 新增功能
HarmonyOS 6新增了一些实用功能:
// 1. 热点流量统计
const hotspotStats = await wifiManager.getHotspotStats();
console.info(`发送: ${hotspotStats.txBytes} 字节`);
console.info(`接收: ${hotspotStats.rxBytes} 字节`);
// 2. 设备限速
await wifiManager.setStationBandwidth(deviceAddress, {
maxDownload: 1024 * 1024, // 1MB/s
maxUpload: 512 * 1024 // 512KB/s
});
// 3. 热点节能模式
await wifiManager.setHotspotPowerSaveMode(true);
// 4. WPA3支持
const config: wifiManager.HotspotConfig = {
ssid: 'MyHotspot',
preSharedKey: 'password123',
securityType: wifiManager.HotspotSecurityType.WIFI_SEC_TYPE_SAE, // WPA3
band: wifiManager.HotspotBandType.HOTSPOT_BAND_TYPE_5G
};
5.3 权限变更
HarmonyOS 6对热点权限进行了细分:
{
"requestPermissions": [
{
"name": "ohos.permission.MANAGE_WIFI_HOTSPOT",
"reason": "管理WiFi热点"
},
{
"name": "ohos.permission.GET_WIFI_HOTSPOT_INFO", // 新增:只读热点信息
"reason": "获取热点状态"
},
{
"name": "ohos.permission.CONTROL_WIFI_HOTSPOT", // 新增:控制热点开关
"reason": "开启/关闭热点"
}
]
}
六、总结
WiFi热点功能为应用开发打开了新的可能性,从智能配网到设备间通信,都有着广泛的应用场景。本文全面讲解了鸿蒙系统中热点管理的核心要点:
核心要点回顾:
- 权限管理:热点功能需要完整的权限配置,缺一不可
- 配置优化:SSID、密码、频段等参数需要根据场景合理设置
- 状态监听:实时感知热点状态和设备连接情况
- 互斥处理:热点与WiFi连接互斥,需要妥善处理切换逻辑
- 兼容性:考虑不同设备的支持能力,做好降级方案
最佳实践建议:
- 使用工具类封装热点管理逻辑,提高代码复用性
- 实现智能频段选择,兼顾性能和兼容性
- 添加完善的错误处理和重试机制
- 做好版本适配,保证向后兼容
下一步学习:
- WiFi P2P点对点通信(下一篇文章)
- 蓝牙通信技术
- 多设备协同技术
- 近场通信方案对比
WiFi热点看似简单,实则涉及权限、配置、状态管理等多个方面。希望本文能帮助你掌握热点开发的完整知识体系,在实际项目中游刃有余!
- 点赞
- 收藏
- 关注作者
评论(0)