连接WiFi p2p android,WIFI_P2P_CONNECTION_CHANGED_ACTION

时间:2016-12-15 10:36:09

标签: android broadcastreceiver wifi-direct wifip2p

我发现同伴,但我无法连接到其中一个。我觉得我的BroadcastReceiver没有得到WIFI_P2P_CONNECTION_CHANGED_ACTION,因为它没有执行里面的内容。

connect():

    public void connect(View v) {
    // Picking the first device found on the network.
    WifiP2pDevice device = (WifiP2pDevice) peers.get(0);

    WifiP2pConfig config = new WifiP2pConfig();
    config.deviceAddress = device.deviceAddress;
    config.wps.setup = WpsInfo.PBC;
    config.groupOwnerIntent = 0;


    mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
            Toast.makeText(MultiActivity.this, "Connect initiated" ,
                    Toast.LENGTH_SHORT).show();

        }

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

onReceive():

else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Connection state changed!  We should probably do something about
        // that.
        Toast.makeText(activity, "ca marche",
                Toast.LENGTH_SHORT).show();

        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);
        }

    }

Toast“ca marche”从未出现在屏幕上。 请帮帮我,谢谢。

2 个答案:

答案 0 :(得分:0)

确保使用正确的IntentFilter注册您的广播接收器。

例如:

  1. 创建新的意图过滤器:IntentFilter tmpFilter = new IntentFilter();
  2. 添加您感兴趣的操作:tmpFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
  3. 将其注册到广播接收器(最好是onResume()):registerReceiver(p2PBroadcastReceiver, tmpFilter)
  4. 你可以在这里找到详细的例子: enter image description here

    古德勒克。

答案 1 :(得分:0)

public void connect(WifiP2pConfig config) {
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
            peerListener.connectionSuccess();
        }

        @Override
        public void onFailure(int reason) {
            peerListener.connectionFailure();
            Toast.makeText(activity, "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
        }
    });
}