Cómo crear conexiones P2P con Wi-Fi directo

La función de Wi-Fi directo (también conocido como entre pares o P2P) le permite a tu aplicación encontrar rápidamente dispositivos cercanos e interactuar con ellos, en un rango que supera la capacidad de Bluetooth.

Las APIs de Wi-Fi directo (P2P) permiten que las aplicaciones se conecten a dispositivos cercanos sin necesidad de conectarse a una red o un hotspot. Si tu app está diseñada para ser parte de una red segura de alcance cercano, Wi-Fi directo es una opción más adecuada que las redes Wi-Fi tradicionales ad hoc por los siguientes motivos:

  • Wi-Fi directo admite encriptación WPA2. (Algunas redes ad hoc solo admiten encriptación WEP).
  • Los dispositivos pueden transmitir los servicios que proporcionan, lo que ayuda a otros dispositivos a descubrir pares adecuados con mayor facilidad.
  • Al determinar qué dispositivo debe ser el propietario del grupo para la red, Wi-Fi directo examina la administración de energía, la IU y las capacidades del servicio de cada dispositivo, y usa esta información para elegir el dispositivo que puede manejar las responsabilidades del servidor de manera más eficaz.
  • Android no admite el modo Wi-Fi ad hoc.

En esta lección, te mostramos cómo encontrar dispositivos cercanos y conectarte a ellos mediante Wi-Fi P2P.

Cómo establecer permisos de aplicaciones

Para usar Wi-Fi directo, agrega los permisos ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE y INTERNET a tu manifiesto. Si tu app se orienta a Android 13 (nivel de API 33) o versiones posteriores, agrega también el permiso NEARBY_WIFI_DEVICES a tu manifiesto. Wi-Fi directo no requiere una conexión a Internet, pero usa sockets estándar de Java, que requieren el permiso INTERNET. Por ello, necesitas los siguientes permisos para usar Wi-Fi directo:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.nsdchat"
    ...
    <!-- If your app targets Android 13 (API level 33)
         or higher, you must declare the NEARBY_WIFI_DEVICES permission. -->
        <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
        <!-- If your app derives location information from Wi-Fi APIs,
             don't include the "usesPermissionFlags" attribute. -->
        android:usesPermissionFlags="neverForLocation" />
        
    <uses-permission
        android:required="true"
        android:name="android.permission.ACCESS_FINE_LOCATION"
        <!-- If any feature in your app relies on precise location information,
             don't include the "maxSdkVersion" attribute. -->
        android:maxSdkVersion="32" />
    <uses-permission
        android:required="true"
        android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission
        android:required="true"
        android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission
        android:required="true"
        android:name="android.permission.INTERNET"/>
    ...

Además de los permisos mencionados, las siguientes API también requieren que se habilite el Modo de ubicación:

Cómo establecer un receptor de emisión y administrador entre pares

Para usar Wi-Fi directo, debes escuchar intents de transmisión que le indican a tu aplicación cuándo ocurrieron ciertos eventos. En tu aplicación, crea una instancia de IntentFilter y configúrala para que escuche lo siguiente:

WIFI_P2P_STATE_CHANGED_ACTION
Indica si Wi-Fi directo está habilitado.
WIFI_P2P_PEERS_CHANGED_ACTION
Indica que cambió la lista de pares disponibles.
WIFI_P2P_CONNECTION_CHANGED_ACTION
Indica que cambió el estado de la conectividad de Wi-Fi directo. A partir de Android 10, este no es un valor fijo. Si tu app dependía de la recepción de estas transmisiones en el registro debido a que eran fijas, en su lugar, usa el método get apropiado en la inicialización para obtener la información.
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
Indica que cambiaron los detalles de configuración de este dispositivo. A partir de Android 10, este no es un valor fijo. Si tu app dependía de la recepción de estas transmisiones en el registro debido a que eran fijas, en su lugar, usa el método get apropiado en la inicialización para obtener la información.

Kotlin

private val intentFilter = IntentFilter()
...
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)

    // Indicates a change in the Wi-Fi Direct status.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)

    // Indicates a change in the list of available peers.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)

    // Indicates the state of Wi-Fi Direct connectivity has changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)

    // Indicates this device's details have changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
    ...
}

Java

private final IntentFilter intentFilter = new IntentFilter();
...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Indicates a change in the Wi-Fi Direct status.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);

    // Indicates a change in the list of available peers.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);

    // Indicates the state of Wi-Fi Direct connectivity has changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);

    // Indicates this device's details have changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    ...
}

Al final del método onCreate(), obtén una instancia de WifiP2pManager y llama a su método initialize(). Este método muestra un objeto WifiP2pManager.Channel, que usarás más adelante para conectar tu app al framework de Wi-Fi directo.

Kotlin

private lateinit var channel: WifiP2pManager.Channel
private lateinit var manager: WifiP2pManager

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
    channel = manager.initialize(this, mainLooper, null)
}

Java

Channel channel;
WifiP2pManager manager;

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
}

Ahora, crea una nueva clase BroadcastReceiver que usarás para escuchar cambios en el estado de Wi-Fi del sistema. En el método onReceive(), agrega una condición para controlar cada cambio de estado mencionado anteriormente.

Kotlin

override fun onReceive(context: Context, intent: Intent) {
    when(intent.action) {
        WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
            // Determine if Wi-Fi Direct mode is enabled or not, alert
            // the Activity.
            val state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1)
            activity.isWifiP2pEnabled = state == WifiP2pManager.WIFI_P2P_STATE_ENABLED
        }
        WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {

            // The peer list has changed! We should probably do something about
            // that.

        }
        WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {

            // Connection state changed! We should probably do something about
            // that.

        }
        WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
            (activity.supportFragmentManager.findFragmentById(R.id.frag_list) as DeviceListFragment)
                    .apply {
                        updateThisDevice(
                                intent.getParcelableExtra(
                                        WifiP2pManager.EXTRA_WIFI_P2P_DEVICE) as WifiP2pDevice
                        )
                    }
        }
    }
}

Java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // Determine if Wi-Fi Direct mode is enabled or not, alert
        // the Activity.
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            activity.setIsWifiP2pEnabled(true);
        } else {
            activity.setIsWifiP2pEnabled(false);
        }
    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

        // The peer list has changed! We should probably do something about
        // that.

    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

        // Connection state changed! We should probably do something about
        // that.

    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
                .findFragmentById(R.id.frag_list);
        fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
                WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));

    }
}

Por último, agrega código para registrar el filtro de intents y el receptor de emisión cuando tu actividad principal esté activa, y para cancelar su registro cuando la actividad esté en pausa. El mejor lugar para hacerlo son los métodos onResume() y onPause().

Kotlin

/** register the BroadcastReceiver with the intent values to be matched  */
public override fun onResume() {
    super.onResume()
    receiver = WiFiDirectBroadcastReceiver(manager, channel, this)
    registerReceiver(receiver, intentFilter)
}

public override fun onPause() {
    super.onPause()
    unregisterReceiver(receiver)
}

Java

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

Cómo iniciar el descubrimiento de pares

Para comenzar a buscar dispositivos cercanos con Wi-Fi P2P, llama a discoverPeers(). Este método adopta los siguientes argumentos:

Kotlin

manager.discoverPeers(channel, object : WifiP2pManager.ActionListener {

    override fun onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank. Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    override fun onFailure(reasonCode: Int) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
})

Java

manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

    @Override
    public void onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank. Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    @Override
    public void onFailure(int reasonCode) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
});

Recuerda que con este procedimiento solo se inicia la búsqueda de pares. El método discoverPeers() inicia el proceso de descubrimiento y, luego, se muestra de inmediato. El sistema te notifica si los métodos de llamada iniciaron correctamente el proceso de descubrimiento de pares en el objeto de escucha de acciones proporcionado. Además, la detección permanece activa hasta que se inicia una conexión o se forma un grupo P2P.

Cómo obtener la lista de pares

Ahora, escribe el código que recupera y procesa la lista de pares. Primero, implementa la interfaz WifiP2pManager.PeerListListener, que proporciona información sobre los pares que detectó Wi-Fi directo. Esta información también permite que tu app determine cuándo los pares se unen a la red o salen de ella. En el siguiente fragmento de código, se ilustran estas operaciones relacionadas con los pares:

Kotlin

private val peers = mutableListOf<WifiP2pDevice>()
...

private val peerListListener = WifiP2pManager.PeerListListener { peerList ->
    val refreshedPeers = peerList.deviceList
    if (refreshedPeers != peers) {
        peers.clear()
        peers.addAll(refreshedPeers)

        // If an AdapterView is backed by this data, notify it
        // of the change. For instance, if you have a ListView of
        // available peers, trigger an update.
        (listAdapter as WiFiPeerListAdapter).notifyDataSetChanged()

        // Perform any other updates needed based on the new list of
        // peers connected to the Wi-Fi P2P network.
    }

    if (peers.isEmpty()) {
        Log.d(TAG, "No devices found")
        return@PeerListListener
    }
}

Java

private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
...

private PeerListListener peerListListener = new PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {

        List<WifiP2pDevice> refreshedPeers = peerList.getDeviceList();
        if (!refreshedPeers.equals(peers)) {
            peers.clear();
            peers.addAll(refreshedPeers);

            // If an AdapterView is backed by this data, notify it
            // of the change. For instance, if you have a ListView of
            // available peers, trigger an update.
            ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();

            // Perform any other updates needed based on the new list of
            // peers connected to the Wi-Fi P2P network.
        }

        if (peers.size() == 0) {
            Log.d(WiFiDirectActivity.TAG, "No devices found");
            return;
        }
    }
}

Ahora, modifica el método onReceive() de tu receptor de emisión para llamar a requestPeers() cuando se reciba un intent con la acción WIFI_P2P_PEERS_CHANGED_ACTION. De alguna manera, debes pasar este objeto de escucha por el receptor. Una forma es enviarlo como un argumento al constructor del receptor de emisión.

Kotlin

fun onReceive(context: Context, intent: Intent) {
    when (intent.action) {
        ...
        WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {

            // Request available peers from the wifi p2p manager. This is an
            // asynchronous call and the calling activity is notified with a
            // callback on PeerListListener.onPeersAvailable()
            mManager?.requestPeers(channel, peerListListener)
            Log.d(TAG, "P2P peers changed")


        }
        ...
    }
}

Java

public void onReceive(Context context, Intent intent) {
    ...
    else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

        // Request available peers from the wifi p2p manager. This is an
        // asynchronous call and the calling activity is notified with a
        // callback on PeerListListener.onPeersAvailable()
        if (mManager != null) {
            mManager.requestPeers(channel, peerListListener);
        }
        Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
    }...
}

Ahora, un intent con el intent WIFI_P2P_PEERS_CHANGED_ACTION de acción activa una solicitud para obtener una lista de pares actualizada.

Cómo conectarse con un par

Para conectarte a un par, crea un objeto WifiP2pConfig nuevo y copia datos en él desde la WifiP2pDevice que representa el dispositivo al que deseas conectarte. Luego, llama al método connect().

Kotlin

override fun connect() {
    // Picking the first device found on the network.
    val device = peers[0]

    val config = WifiP2pConfig().apply {
        deviceAddress = device.deviceAddress
        wps.setup = WpsInfo.PBC
    }

    manager.connect(channel, config, object : WifiP2pManager.ActionListener {

        override fun onSuccess() {
            // WiFiDirectBroadcastReceiver notifies us. Ignore for now.
        }

        override fun onFailure(reason: Int) {
            Toast.makeText(
                    this@WiFiDirectActivity,
                    "Connect failed. Retry.",
                    Toast.LENGTH_SHORT
            ).show()
        }
    })
}

Java

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

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

    manager.connect(channel, config, new ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver notifies us. Ignore for now.
        }

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

Si cada uno de los dispositivos del grupo admite Wi-Fi directo, no necesitas solicitar explícitamente la contraseña del grupo durante la conexión. Sin embargo, para permitir que un dispositivo que no admite Wi-Fi directo se una a un grupo, debes recuperar esta contraseña llamando a requestGroupInfo(), como se muestra en el siguiente fragmento de código:

Kotlin

manager.requestGroupInfo(channel) { group ->
    val groupPassword = group.passphrase
}

Java

manager.requestGroupInfo(channel, new GroupInfoListener() {
  @Override
  public void onGroupInfoAvailable(WifiP2pGroup group) {
      String groupPassword = group.getPassphrase();
  }
});

Ten en cuenta que el WifiP2pManager.ActionListener implementado en el método connect() solo te notifica cuando la iniciación se completa correctamente o falla. Para escuchar cambios en el estado de conexión, implementa la interfaz WifiP2pManager.ConnectionInfoListener. Su devolución de llamada onConnectionInfoAvailable() te notifica cuando cambia el estado de la conexión. En los casos en los que se conectarán varios dispositivos a uno solo (como en un juego con tres o más jugadores, o una app de chat), se designa a un dispositivo como "propietario del grupo". Para designar un dispositivo en particular como el propietario del grupo de la red, sigue los pasos de la sección Cómo crear un grupo.

Kotlin

private val connectionListener = WifiP2pManager.ConnectionInfoListener { info ->

    // String from WifiP2pInfo struct
    val groupOwnerAddress: String = info.groupOwnerAddress.hostAddress

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

Java

@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {

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

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

Ahora, vuelve al método onReceive() del receptor de emisión y modifica la sección que escucha un intent WIFI_P2P_CONNECTION_CHANGED_ACTION. Cuando se reciba este intent, llama a requestConnectionInfo(). Esta es una llamada asíncrona, por lo que los resultados se reciben en el objeto de escucha de información de conexión que proporcionas como parámetro.

Kotlin

when (intent.action) {
    ...
    WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {

        // Connection state changed! We should probably do something about
        // that.

        mManager?.let { manager ->

            val networkInfo: NetworkInfo? = intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO) as NetworkInfo

            if (networkInfo?.isConnected == true) {

                // We are connected with the other device, request connection
                // info to find group owner IP

                manager.requestConnectionInfo(channel, connectionListener)
            }
        }
    }
    ...
}

Java

    ...
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

        if (manager == 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

            manager.requestConnectionInfo(channel, connectionListener);
        }
        ...

Crear un grupo

Si deseas que el dispositivo que ejecuta tu app funcione como propietario del grupo en una red que incluye dispositivos heredados (es decir, dispositivos que no admiten Wi-Fi directo), debes seguir la misma secuencia de pasos que en la sección Conectarse con un par, excepto que debes crear una nueva WifiP2pManager.ActionListener con createGroup() en lugar de connect(). El control de devolución de llamada dentro de WifiP2pManager.ActionListener es el mismo, como se muestra en el siguiente fragmento de código:

Kotlin

manager.createGroup(channel, object : WifiP2pManager.ActionListener {
    override fun onSuccess() {
        // Device is ready to accept incoming connections from peers.
    }

    override fun onFailure(reason: Int) {
        Toast.makeText(
                this@WiFiDirectActivity,
                "P2P group creation failed. Retry.",
                Toast.LENGTH_SHORT
        ).show()
    }
})

Java

manager.createGroup(channel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
        // Device is ready to accept incoming connections from peers.
    }

    @Override
    public void onFailure(int reason) {
        Toast.makeText(WiFiDirectActivity.this, "P2P group creation failed. Retry.",
                Toast.LENGTH_SHORT).show();
    }
});

Nota: Si todos los dispositivos de una red admiten Wi-Fi directo, puedes usar el método connect() en cada uno, ya que este crea el grupo y selecciona automáticamente un propietario.

Después de crear un grupo, puedes llamar a requestGroupInfo() para recuperar detalles sobre los pares de la red, incluidos los nombres de los dispositivos y los estados de conexión.