WIFI_P2P_CONNECTION_CHANGED_ACTION,Wifi Direct,Android

时间:2012-08-13 08:58:04

标签: android broadcastreceiver wifi-direct

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

1 个答案:

答案 0 :(得分:5)

如文档[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