WIFI_P2P_CONNECTION_CHANGED_ACTION, Wifi Direct, Android

Posted

技术标签:

【中文标题】WIFI_P2P_CONNECTION_CHANGED_ACTION, Wifi Direct, Android【英文标题】: 【发布时间】:2012-08-13 08:58:04 【问题描述】:

我正在尝试在 android 中使用 Wifi-direct 连接两个 P2p 设备。我确保我拥有所有需要的permissions,并且Broadcast Receiver 已注册。但我仍然没有听WIFI_P2P_CONNECTION_CHANGED_ACTION 行动。请建议我克服这个问题或建议我其他解决方案。谢谢。

【问题讨论】:

【参考方案1】:

如文档[1] 中所示,您可以通过这种方式实现连接。

 public void connect() 

    WifiP2pConfig config = new WifiP2pConfig();
    config.deviceAddress = "DEVICE_TO_CONNECT_MAC_ADDRESS";
    config.wps.setup = WpsInfo.PBC;

    mManager.connect(mChannel, config, new ActionListener() 

        @Override
        public void onSuccess() 
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
        

        @Override
        public void onFailure(int reason) 
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        
    );

之后,修改 BroadcastReceiver 以便使用 WifiP2pManager 的实例请求连接信息,如

if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) 

    if (mManager == null) 
         return;
    
    NetworkInfo networkInfo = (NetworkInfo) intent
               .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

    if (networkInfo.isConnected()) 
         // We are connected with the other device, request connection
         // info to find group owner IP

         mManager.requestConnectionInfo(mChannel, connectionListener);
    

此块应在侦听 WIFI_P2P_CONNECTION_CHANGED_ACTION 意图的 BrodacastReceiver 上实现。

现在,实现接口 WifiP2pManager.ConnectionInfoListener[2]。

@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) 

    // InetAddress from WifiP2pInfo struct.
    InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress());

    // After the group negotiation, we can determine the group owner.
    if (info.groupFormed && info.isGroupOwner) 
        // Do whatever tasks are specific to the group owner.
        // One common case is creating a server thread and accepting
        // incoming connections.
     else if (info.groupFormed) 
        // The other device acts as the client. In this case,
        // you'll want to create a client thread that connects to the group
        // owner.
    

希望对您有所帮助。 :)

[1] - http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html#connect

[2] - http://developer.android.com/reference/android/net/wifi/p2p/WifiP2pManager.ConnectionInfoListener.html

【讨论】:

以上是关于WIFI_P2P_CONNECTION_CHANGED_ACTION, Wifi Direct, Android的主要内容,如果未能解决你的问题,请参考以下文章

为啥广播接收器没有检测到 WIFI_P2P_CONNECTION_CHANGED_ACTION?

WiFi-Direct 获取设备名称

Wifi直连(p2p)一对多音频传输