1

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

4

1 回答 1

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-wireless/wifi-direct.html#connect

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

于 2012-11-20T17:16:44.410 回答