阅读(189) (0)

鸿蒙OS WLAN消息通知

2020-09-17 10:00:51 更新

场景介绍

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

接口说明

描述 通知名 附加参数
WLAN状态 usual.event.wifi.POWER_STATE active_state
WLAN扫描 usual.event.wifi.SCAN_FINISHED scan_state
WLAN RSSI变化 usual.event.wifi.RSSI_VALUE rssi_value
WLAN连接状态 usual.event.wifi.CONN_STATE conn_state
Hotspot状态 usual.event.wifi.HOTSPOT_STATE hotspot_active_state
Hotspot连接状态 usual.event.wifi.WIFI_HS_STA_JOIN usual.event.wifi.WIFI_HS_STA_LEAVE -
P2P状态 usual.event.wifi.p2p.STATE_CHANGE p2p_state
P2P连接状态 usual.event.wifi.p2p.CONN_STATE_CHANGE linked_infonet_infogroup_info
P2P设备列表变化 usual.event.wifi.p2p.PEERS_STATE_CHANGE peers_list
P2P搜索状态变化 usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE peers_discovery
P2P当前设备变化 usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE p2p_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!");
   }