鸿蒙OS开发文档 鸿蒙OS WLAN消息通知

2024-02-25 开发教程 鸿蒙OS开发文档 匿名 3

场景介绍

WLAN 消息通知(Notification)是 HarmonyOS 内部或者与应用之间跨进程通讯的机制,注册者在注册消息通知后,一旦符合条件的消息被发出,注册者即可接收到该消息并获取消息中附带的信息。

接口说明

描述通知名附加参数
WLAN状态usual.event.wifi.POWER_STATEactive_state
WLAN扫描usual.event.wifi.SCAN_FINISHEDscan_state
WLAN RSSI变化usual.event.wifi.RSSI_VALUErssi_value
WLAN连接状态usual.event.wifi.CONN_STATEconn_state
Hotspot状态usual.event.wifi.HOTSPOT_STATEhotspot_active_state
Hotspot连接状态usual.event.wifi.WIFI_HS_STA_JOIN usual.event.wifi.WIFI_HS_STA_LEAVE-
P2P状态usual.event.wifi.p2p.STATE_CHANGEp2p_state
P2P连接状态usual.event.wifi.p2p.CONN_STATE_CHANGElinked_infonet_infogroup_info
P2P设备列表变化usual.event.wifi.p2p.PEERS_STATE_CHANGEpeers_list
P2P搜索状态变化usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGEpeers_discovery
P2P当前设备变化usual.event.wifi.p2p.CURRENT_DEVICE_CHANGEp2p_device
P2P群组信息变化usual.event.wifi.p2p.GROUP_STATE_CHANGED-

开发步骤

  1. 构建消息通知接收者 WifiEventSubscriber。
  1. 注册 WLAN 变化消息。
  1. WifiEventSubscriber 接收并处理 WLAN 广播消息。
// 构建消息接收者/注册者
class WifiEventSubscriber extends CommonEventSubscriber {
WifiEventSubscriber (CommonEventSubscribeInfo info) {
super(info);
}
@Override
public void onReceiveEvent(CommonEventData commonEventData) {
if (WifiEvents.EVENT_ACTIVE_STATE.equals(commonEventData.getIntent().getAction())) {
// 获取附带参数
IntentParams params = commonEventData.getIntent().getParams();
if (params == null) {
return;
}
int wifiState= (int) params.getParam(WifiEvents.PARAM_ACTIVE_STATE);
if (wifiState== WifiEvents.STATE_ACTIVE) { // 处理WLAN被打开消息
HiLog.info(LABEL, false, "Receive WifiEvents.STATE_ACTIVE %{public}d", wifiState);
} else if (wifiState == WifiEvents.STATE_INACTIVE) { // 处理WLAN被关闭消息
HiLog.info(LABEL, false, "Receive WifiEvents.STATE_INACTIVE %{public}d", wifiState);
} else { // 处理WLAN异常状态
HiLog.info(LABEL, false, "Unknown wifi state");
}
}
}
}
// 注册消息
MatchingSkills match = new MatchingSkills();
// 增加获取WLAN状态变化消息
filter.addEvent(WifiEvents.EVENT_ACTIVE_STATE);
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(match);
subscribeInfo.setPriority(100);
WifiEventSubscriber subscriber = new WifiEventSubscriber(subscribeInfo);
try {
CommonEventManager.subscribeCommonEvent(subscriber);
} catch (RemoteException e) {
HiLog.warn(LABEL, false, "subscribe in wifi events failed!");
}