Wi-Fi directo (también conocido como entre pares o P2P) permite que tu app encuentre e interactúe rápidamente con dispositivos cercanos en un rango que supera la capacidad de Bluetooth.
Las API de Wi-Fi directo (P2P) permiten que las aplicaciones se conecten a dispositivos cercanos sin 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 Direct 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 brindan, lo que ayuda a otros los dispositivos descubran apps similares adecuadas con mayor facilidad.
- Cuando determina qué dispositivo debería ser el propietario del grupo en la red, Wi-Fi Direct examina la administración de energía, la IU y las capacidades de servicio de cada dispositivo y usa esta información para elegir el dispositivo que pueda manejar las responsabilidades del servidor con mayor eficacia.
- 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
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, también agrega el atributo
NEARBY_WIFI_DEVICES
permiso en tu manifiesto. Wi‐Fi
El acceso directo no requiere una conexión a Internet, pero usa Java estándar
sockets, lo que requiere el INTERNET
permiso. Por lo tanto, necesitas los siguientes permisos para usar Wi-Fi Direct:
<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 anteriores, 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 detectar intents de transmisión que le indiquen a tu
cuando ocurren ciertos eventos. En la aplicación, crea una instancia de IntentFilter
y configúrala para escuchar 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 apps similares disponibles.
WIFI_P2P_CONNECTION_CHANGED_ACTION
-
Indica que cambió el estado de la conectividad Wi-Fi Direct. A partir de Android 10, este no es un valor fijo. Si tu app dependía de recibir estas
debido a que estaban fijas, usa el
get
adecuado en la inicialización para obtener la información en su lugar. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
-
Indica que cambiaron los detalles de configuración de este dispositivo. Para empezar
Android 10 no es 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.
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) ... }
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 la app al framework de Wi-Fi Direct.
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) }
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 de BroadcastReceiver
que usarás para escuchar los cambios
al estado de Wi-Fi del sistema. En el método onReceive()
, agrega una condición para controlar cada cambio de estado indicado anteriormente.
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 ) } } } }
@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 la actividad principal esté activa, y para cancelar el registro de estos cuando la actividad esté detenida.
El mejor lugar para hacerlo son los métodos onResume()
y onPause()
.
/** 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) }
/** 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 toma los siguientes argumentos:
- El
WifiP2pManager.Channel
que recibiste cuando inicializaste el mManager entre pares. - Una implementación de
WifiP2pManager.ActionListener
con métodos que invoca el sistema para el descubrimiento exitoso y no exitoso.
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. } })
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, muestra los resultados de inmediato. El sistema te notifica si el proceso de detección
se inicia correctamente a través de los métodos de llamada en el objeto de escucha de acciones proporcionado.
Además, la detección permanece activa hasta que se inicia una conexión o se inicia 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 Direct. Esta información también le permite a la app determinar 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 apps similares:
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 } }
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 onReceive()
de tu receptor de emisión
para llamar a requestPeers()
cuando se recibe un intent con la acción WIFI_P2P_PEERS_CHANGED_ACTION
. Tú
tendrás que pasar este objeto de escucha por el receptor de alguna manera. Una manera es enviarlo como un argumento al constructor del receptor de emisión.
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") } ... } }
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 de una lista de pares actualizada.
Cómo conectarse con un par
Para conectarte a un par, crea un nuevo objeto WifiP2pConfig
y copia datos desde la
WifiP2pDevice
, que representa el dispositivo que deseas
a la que te conectarás. Luego, llama al connect()
.
.
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() } }) }
@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 es necesario
para solicitar explícitamente la contraseña del grupo al establecer conexión. Sin embargo, para permitir que un dispositivo que no admite Wi-Fi directo se una a un grupo, debes recuperar la contraseña llamando a requestGroupInfo()
, como se muestra en el siguiente fragmento de código:
manager.requestGroupInfo(channel) { group -> val groupPassword = group.passphrase }
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
es correcta o falla. Para detectar cambios en el estado de conexión, implementa
WifiP2pManager.ConnectionInfoListener
.
Su devolución de llamada onConnectionInfoAvailable()
te notifica cuando el estado de la
los cambios de conexión. En los casos en 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 un dispositivo como "propietario del grupo". Para designar un dispositivo en particular como propietario del grupo de la red, sigue los pasos de la sección Cómo crear un grupo.
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. } }
@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, regresa 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, de modo que los resultados se reciben en el objeto de escucha de información de conexión que proporcionas como un parámetro.
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) } } } ... }
... } 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); } ...
Cómo crear un grupo
Si quieres que el dispositivo que ejecuta tu app funcione como el propietario del grupo durante un
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 Conéctate a un dispositivo similar, excepto que creas una nueva
WifiP2pManager.ActionListener
con createGroup()
en lugar de connect()
. El control de la devolución de llamada dentro de WifiP2pManager.ActionListener
es el mismo, como se muestra en el siguiente fragmento de código:
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() } })
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 son compatibles con Wi-Fi.
Directo, puedes usar el método connect()
en cada dispositivo porque el
Luego, crea el grupo y selecciona automáticamente un propietario del grupo.
Después de crear un grupo, puedes llamar
requestGroupInfo()
para recuperar detalles sobre los intercambios de tráfico en
la red, incluidos los nombres de los dispositivos y los estados de conexión.