Établir des connexions P2P avec Wi-Fi Direct

Wi-Fi Direct (également appelé peer-to-peer ou P2P) permet à votre application de trouver rapidement des appareils à proximité et d'interagir avec eux, à une distance supérieure à celle du Bluetooth.

Les API Wi-Fi Direct (P2P) permettent aux applications de se connecter à des appareils à proximité sans avoir à se connecter à un réseau ni à un point d'accès. Si votre application est conçue pour faire partie d'un réseau sécurisé à courte portée, Wi-Fi Direct est une option plus appropriée que la mise en réseau ad hoc Wi-Fi traditionnelle pour les raisons suivantes :

  • Wi-Fi Direct est compatible avec le chiffrement WPA2. (Certains réseaux ad hoc ne sont compatibles qu'avec le chiffrement WEP.)
  • Les appareils peuvent diffuser les services qu'ils fournissent, ce qui aide les autres appareils à découvrir plus facilement les pairs appropriés.
  • Pour déterminer quel appareil doit être le propriétaire du groupe pour le réseau, Wi-Fi Direct examine les capacités de gestion de l'alimentation, d'UI et de service de chaque appareil, et utilise ces informations pour choisir l'appareil qui peut gérer les responsabilités du serveur le plus efficacement possible.
  • Android n'est pas compatible avec le mode Wi-Fi ad hoc.

Cette leçon vous explique comment trouver des appareils à proximité et vous y connecter à l'aide du Wi-Fi P2P.

Configurer les autorisations d'application

Pour utiliser Wi-Fi Direct, ajoutez les autorisations ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE et INTERNET à votre fichier manifeste. Si votre application cible Android 13 (niveau d'API 33) ou version ultérieure, ajoutez également l'autorisation NEARBY_WIFI_DEVICES à votre fichier manifeste. Wi-Fi Direct ne nécessite pas de connexion Internet, mais utilise des sockets Java standards, ce qui nécessite l'autorisation INTERNET. Vous avez donc besoin des autorisations suivantes pour utiliser 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"/>
    ...

En plus des autorisations précédentes, les API suivantes nécessitent également que le mode Localisation soit activé :

Configurer un broadcast receiver et un gestionnaire peer-to-peer

Pour utiliser Wi-Fi Direct, vous devez écouter les intents de diffusion qui indiquent à votre application quand certains événements se sont produits. Dans votre application, instanciez un IntentFilter et configurez-le pour qu'il écoute les éléments suivants :

WIFI_P2P_STATE_CHANGED_ACTION
Indique si Wi-Fi Direct est activé.
WIFI_P2P_PEERS_CHANGED_ACTION
Indique que la liste des pairs disponibles a changé.
WIFI_P2P_CONNECTION_CHANGED_ACTION
Indique que l'état de la connectivité Wi-Fi Direct a changé. À partir d'Android 10, cette valeur n'est pas persistante. Si votre application s'est appuyée sur la réception de ces diffusions lors de l'enregistrement, car elles étaient persistantes, utilisez la méthode get appropriée lors de l'initialisation pour obtenir les informations à la place.
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
Indique que les détails de configuration de cet appareil ont été modifiés. À partir d'Android 10, cette valeur n'est pas persistante. Si votre application s'est appuyée sur la réception de ces diffusions lors de l'enregistrement, car elles étaient persistantes, utilisez la méthode get appropriée lors de l'initialisation pour obtenir les informations à la place.

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

À la fin de la méthode onCreate(), obtenez une instance de WifiP2pManager et appelez sa méthode initialize(). Cette méthode renvoie un objet WifiP2pManager.Channel, que vous utiliserez ultérieurement pour connecter votre application au framework Wi-Fi Direct.

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

Créez maintenant une classe BroadcastReceiver que vous utiliserez pour écouter les modifications apportées à l'état du Wi-Fi du système. Dans la méthode onReceive(), ajoutez une condition pour gérer chaque changement d'état listé ci-dessus.

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

    }
}

Enfin, ajoutez du code pour enregistrer le filtre d'intent et le récepteur de diffusion lorsque votre activité principale est active, et pour les désenregistrer lorsque l'activité est suspendue. Le meilleur endroit pour le faire est dans les méthodes onResume() et 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);
}

Lancer la découverte de pairs

Pour commencer à rechercher des appareils à proximité avec le Wi-Fi P2P, appelez discoverPeers(). Cette méthode utilise les arguments suivants :

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

N'oubliez pas que cette méthode ne fait que lancer la découverte des pairs. La méthode discoverPeers() lance le processus de découverte, puis renvoie immédiatement. Le système vous avertit si le processus de découverte des pairs est correctement lancé en appelant des méthodes dans l'écouteur d'actions fourni. De plus, la découverte reste active jusqu'à ce qu'une connexion soit établie ou qu'un groupe P2P soit formé.

Récupérer la liste des pairs

Écrivez maintenant le code qui récupère et traite la liste des pairs. Commencez par implémenter l'interface WifiP2pManager.PeerListListener, qui fournit des informations sur les pairs détectés par Wi-Fi Direct. Ces informations permettent également à votre application de déterminer quand des pairs rejoignent ou quittent le réseau. L'extrait de code suivant illustre ces opérations liées aux pairs :

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

Modifiez maintenant la méthode onReceive() de votre récepteur de diffusion pour appeler requestPeers() lorsqu'une intention avec l'action WIFI_P2P_PEERS_CHANGED_ACTION est reçue. Vous devez transmettre cet écouteur au récepteur d'une manière ou d'une autre. Une façon de le faire est de l'envoyer en tant qu'argument au constructeur du broadcast receiver.

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

Désormais, une intention avec l'action WIFI_P2P_PEERS_CHANGED_ACTION déclenche une demande de liste de pairs mise à jour.

Se connecter à un pair

Pour vous connecter à un pair, créez un objet WifiP2pConfig et copiez-y les données à partir de l'WifiP2pDevice représentant l'appareil auquel vous souhaitez vous connecter. Appelez ensuite la méthode 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 chacun des appareils de votre groupe est compatible avec le Wi-Fi Direct, vous n'avez pas besoin de demander explicitement le mot de passe du groupe lors de la connexion. Toutefois, pour autoriser un appareil qui ne prend pas en charge Wi-Fi Direct à rejoindre un groupe, vous devez récupérer ce mot de passe en appelant requestGroupInfo(), comme indiqué dans l'extrait de code suivant :

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

Notez que le WifiP2pManager.ActionListener implémenté dans la méthode connect() ne vous avertit que lorsque l'initiation réussit ou échoue. Pour écouter les modifications de l'état de la connexion, implémentez l'interface WifiP2pManager.ConnectionInfoListener. Son rappel onConnectionInfoAvailable() vous avertit lorsque l'état de la connexion change. Dans le cas où plusieurs appareils doivent être connectés à un seul appareil (par exemple, un jeu avec trois joueurs ou plus, ou une application de chat), un appareil est désigné comme "propriétaire du groupe". Vous pouvez désigner un appareil spécifique comme propriétaire du groupe du réseau en suivant la procédure décrite dans la section Créer un groupe.

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.
    }
}

Revenez maintenant à la méthode onReceive() du récepteur de diffusion et modifiez la section qui écoute un intent WIFI_P2P_CONNECTION_CHANGED_ACTION. Lorsque cet intent est reçu, appelez requestConnectionInfo(). Il s'agit d'un appel asynchrone. Les résultats sont donc reçus par l'écouteur d'informations de connexion que vous fournissez en tant que paramètre.

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

Créer un groupe

Si vous souhaitez que l'appareil sur lequel votre application s'exécute serve de propriétaire du groupe pour un réseau incluant des appareils anciens (c'est-à-dire des appareils qui ne sont pas compatibles avec Wi-Fi Direct), vous devez suivre la même séquence d'étapes que dans la section Se connecter à un pair, sauf que vous devez créer un WifiP2pManager.ActionListener à l'aide de createGroup() au lieu de connect(). La gestion des rappels dans WifiP2pManager.ActionListener est la même, comme indiqué dans l'extrait de code suivant :

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

Remarque  : Si tous les appareils d'un réseau sont compatibles avec Wi-Fi Direct, vous pouvez utiliser la méthode connect() sur chaque appareil, car elle crée ensuite le groupe et sélectionne automatiquement un propriétaire de groupe.

Une fois que vous avez créé un groupe, vous pouvez appeler requestGroupInfo() pour récupérer des informations sur les pairs du réseau, y compris les noms des appareils et les états de connexion.