Create P2P connections with Wi-Fi Direct

Wi-Fi Direct (also known as peer-to-peer or P2P) allows your application to quickly find and interact with nearby devices, at a range beyond the capabilities of Bluetooth.

The Wi-Fi Direct (P2P) APIs allow applications to connect to nearby devices without needing to connect to a network or hotspot. If your app is designed to be a part of a secure, near-range network, Wi-Fi Direct is a more suitable option than traditional Wi-Fi ad-hoc networking for the following reasons:

  • Wi-Fi Direct supports WPA2 encryption. (Some ad-hoc networks support only WEP encryption.)
  • Devices can broadcast the services that they provide, which helps other devices discover suitable peers more easily.
  • When determining which device should be the group owner for the network, Wi-Fi Direct examines each device's power management, UI, and service capabilities and uses this information to choose the device that can handle server responsibilities most effectively.
  • Android doesn't support Wi-Fi ad-hoc mode.

This lesson shows you how to find and connect to nearby devices using Wi-Fi P2P.

Set up application permissions

To use Wi-Fi Direct, add the ACCESS_FINE_LOCATION , CHANGE_WIFI_STATE , ACCESS_WIFI_STATE , and INTERNET permissions to your manifest. If your app targets Android 13 (API level 33) or higher, also add the NEARBY_WIFI_DEVICES permission to your manifest. Wi-Fi Direct doesn't require an internet connection, but it does use standard Java sockets, which requires the INTERNET permission. So you need the following permissions to use Wi-Fi Direct:

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.nsdchat"
...
<!--IfyourapptargetsAndroid 13(APIlevel 33)
orhigher,youmustdeclaretheNEARBY_WIFI_DEVICESpermission.-->
<uses-permissionandroid:name="android.permission.NEARBY_WIFI_DEVICES"
<!--IfyourappderiveslocationinformationfromWi-FiAPIs,
don'tincludethe"usesPermissionFlags"attribute.-->
android:usesPermissionFlags="neverForLocation"/>

<uses-permission
android:required="true"
android:name="android.permission.ACCESS_FINE_LOCATION"
<!--Ifanyfeatureinyourappreliesonpreciselocationinformation,
don'tincludethe"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"/>
...

Besides the preceding permissions, the following APIs also require Location Mode to be enabled:

Set up a broadcast receiver and peer-to-peer manager

To use Wi-Fi Direct, you need to listen for broadcast intents that tell your application when certain events have occurred. In your application, instantiate an IntentFilter and set it to listen for the following:

WIFI_P2P_STATE_CHANGED_ACTION
Indicates whether Wi-Fi Direct is enabled
WIFI_P2P_PEERS_CHANGED_ACTION
Indicates that the available peer list has changed.
WIFI_P2P_CONNECTION_CHANGED_ACTION
Indicates the state of Wi-Fi Direct connectivity has changed. Starting with Android 10, this is not sticky. If your app has relied on receiving these broadcasts at registration because they had been sticky, use the appropriate get method at initialization to obtain the information instead.
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
Indicates this device's configuration details have changed. Starting with Android 10, this is not sticky. If your app has relied on receiving these broadcasts at registration because they had been sticky, use the appropriate get method at initialization to obtain the information instead.

Kotlin

privatevalintentFilter=IntentFilter()
...
overridefunonCreate(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

privatefinalIntentFilterintentFilter=newIntentFilter();
...
@Override
publicvoidonCreate(BundlesavedInstanceState){
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);
...
}

At the end of the onCreate() method, get an instance of the WifiP2pManager , and call its initialize() method. This method returns a WifiP2pManager.Channel object, which you'll use later to connect your app to the Wi-Fi Direct framework.

Kotlin

privatelateinitvarchannel:WifiP2pManager.Channel
privatelateinitvarmanager:WifiP2pManager
overridefunonCreate(savedInstanceState:Bundle?){
...
manager=getSystemService(Context.WIFI_P2P_SERVICE)asWifiP2pManager
channel=manager.initialize(this,mainLooper,null)
}

Java

Channelchannel;
WifiP2pManagermanager;
@Override
publicvoidonCreate(BundlesavedInstanceState){
...
manager=(WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
channel=manager.initialize(this,getMainLooper(),null);
}

Now create a new BroadcastReceiver class that you'll use to listen for changes to the system's Wi-Fi state. In the onReceive() method, add a condition to handle each state change listed above.

Kotlin

overridefunonReceive(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.
valstate=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)asDeviceListFragment)
.apply{
updateThisDevice(
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)asWifiP2pDevice
)
}
}
}
}

Java

@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
// Determine if Wi-Fi Direct mode is enabled or not, alert
// the Activity.
intstate=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
activity.setIsWifiP2pEnabled(true);
}else{
activity.setIsWifiP2pEnabled(false);
}
}elseif(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
// The peer list has changed! We should probably do something about
// that.
}elseif(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
// Connection state changed! We should probably do something about
// that.
}elseif(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
DeviceListFragmentfragment=(DeviceListFragment)activity.getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.updateThisDevice((WifiP2pDevice)intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
}
}

Finally, add code to register the intent filter and broadcast receiver when your main activity is active, and unregister them when the activity is paused. The best place to do this is the onResume() and onPause() methods.

Kotlin

/** register the BroadcastReceiver with the intent values to be matched */
publicoverridefunonResume(){
super.onResume()
receiver=WiFiDirectBroadcastReceiver(manager,channel,this)
registerReceiver(receiver,intentFilter)
}
publicoverridefunonPause(){
super.onPause()
unregisterReceiver(receiver)
}

Java

/** register the BroadcastReceiver with the intent values to be matched */
@Override
publicvoidonResume(){
super.onResume();
receiver=newWiFiDirectBroadcastReceiver(manager,channel,this);
registerReceiver(receiver,intentFilter);
}
@Override
publicvoidonPause(){
super.onPause();
unregisterReceiver(receiver);
}

Initiate peer discovery

To start searching for nearby devices with Wi-Fi P2P, call discoverPeers() . This method takes the following arguments:

Kotlin

manager.discoverPeers(channel,object:WifiP2pManager.ActionListener{
overridefunonSuccess(){
// 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.
}
overridefunonFailure(reasonCode:Int){
// Code for when the discovery initiation fails goes here.
// Alert the user that something went wrong.
}
})

Java

manager.discoverPeers(channel,newWifiP2pManager.ActionListener(){
@Override
publicvoidonSuccess(){
// 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
publicvoidonFailure(intreasonCode){
// Code for when the discovery initiation fails goes here.
// Alert the user that something went wrong.
}
});

Keep in mind that this only initiates peer discovery. The discoverPeers() method starts the discovery process and then immediately returns. The system notifies you if the peer discovery process is successfully initiated by calling methods in the provided action listener. Also, discovery remains active until a connection is initiated or a P2P group is formed.

Fetch the list of peers

Now write the code that fetches and processes the list of peers. First implement the WifiP2pManager.PeerListListener interface, which provides information about the peers that Wi-Fi Direct has detected. This information also allows your app to determine when peers join or leave the network. The following code snippet illustrates these operations related to peers:

Kotlin

privatevalpeers=mutableListOf<WifiP2pDevice>()
...
privatevalpeerListListener=WifiP2pManager.PeerListListener{peerList->
valrefreshedPeers=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.
(listAdapterasWiFiPeerListAdapter).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

privateList<WifiP2pDevice>peers=newArrayList<WifiP2pDevice>();
...
privatePeerListListenerpeerListListener=newPeerListListener(){
@Override
publicvoidonPeersAvailable(WifiP2pDeviceListpeerList){
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;
}
}
}

Now modify your broadcast receiver's onReceive() method to call requestPeers() when an intent with the action WIFI_P2P_PEERS_CHANGED_ACTION is received. You need to pass this listener into the receiver somehow. One way is to send it as an argument to the broadcast receiver's constructor.

Kotlin

funonReceive(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

publicvoidonReceive(Contextcontext,Intentintent){
...
elseif(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");
}...
}

Now, an intent with the action WIFI_P2P_PEERS_CHANGED_ACTION intent triggers a request for an updated peer list.

Connect to a peer

In order to connect to a peer, create a new WifiP2pConfig object, and copy data into it from the WifiP2pDevice representing the device you want to connect to. Then call the connect() method.

Kotlin

overridefunconnect(){
// Picking the first device found on the network.
valdevice=peers[0]
valconfig=WifiP2pConfig().apply{
deviceAddress=device.deviceAddress
wps.setup=WpsInfo.PBC
}
manager.connect(channel,config,object:WifiP2pManager.ActionListener{
overridefunonSuccess(){
// WiFiDirectBroadcastReceiver notifies us. Ignore for now.
}
overridefunonFailure(reason:Int){
Toast.makeText(
this@WiFiDirectActivity,
"Connect failed. Retry.",
Toast.LENGTH_SHORT
).show()
}
})
}

Java

@Override
publicvoidconnect(){
// Picking the first device found on the network.
WifiP2pDevicedevice=peers.get(0);
WifiP2pConfigconfig=newWifiP2pConfig();
config.deviceAddress=device.deviceAddress;
config.wps.setup=WpsInfo.PBC;
manager.connect(channel,config,newActionListener(){
@Override
publicvoidonSuccess(){
// WiFiDirectBroadcastReceiver notifies us. Ignore for now.
}
@Override
publicvoidonFailure(intreason){
Toast.makeText(WiFiDirectActivity.this,"Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}

If each of the devices in your group supports Wi-Fi direct, you don't need to explicitly ask for the group's password when connecting. To allow a device that doesn't support Wi-Fi Direct to join a group, however, you need to retrieve this password by calling requestGroupInfo() , as shown in the following code snippet:

Kotlin

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

Java

manager.requestGroupInfo(channel,newGroupInfoListener(){
@Override
publicvoidonGroupInfoAvailable(WifiP2pGroupgroup){
StringgroupPassword=group.getPassphrase();
}
});

Note that the WifiP2pManager.ActionListener implemented in the connect() method only notifies you when the initiation succeeds or fails. To listen for changes in connection state, implement the WifiP2pManager.ConnectionInfoListener interface. Its onConnectionInfoAvailable() callback notifies you when the state of the connection changes. In cases where multiple devices are going to be connected to a single device (like a game with three or more players, or a chat app), one device is designated the "group owner". You can designate a particular device as the network's group owner by following the steps in the Create a Group section.

Kotlin

privatevalconnectionListener=WifiP2pManager.ConnectionInfoListener{info->
// String from WifiP2pInfo struct
valgroupOwnerAddress: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.
}elseif(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
publicvoidonConnectionInfoAvailable(finalWifiP2pInfoinfo){
// String from WifiP2pInfo struct
StringgroupOwnerAddress=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.
}elseif(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.
}
}

Now go back to the onReceive() method of the broadcast receiver, and modify the section that listens for a WIFI_P2P_CONNECTION_CHANGED_ACTION intent. When this intent is received, call requestConnectionInfo() . This is an asynchronous call, so results are received by the connection info listener you provide as a parameter.

Kotlin

when(intent.action){
...
WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION->{
// Connection state changed! We should probably do something about
// that.
mManager?.let{manager->
valnetworkInfo:NetworkInfo? =intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO)asNetworkInfo
if(networkInfo?.isConnected==true){
// We are connected with the other device, request connection
// info to find group owner IP
manager.requestConnectionInfo(channel,connectionListener)
}
}
}
...
}

Java

...
}elseif(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(manager==null){
return;
}
NetworkInfonetworkInfo=(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);
}
...

Create a group

If you want the device running your app to serve as the group owner for a network that includes legacy devices—that is, devices that don't support Wi-Fi Direct—you follow the same sequence of steps as in the Connect to a Peer section, except you create a new WifiP2pManager.ActionListener using createGroup() instead of connect() . The callback handling within the WifiP2pManager.ActionListener is the same, as shown in the following code snippet:

Kotlin

manager.createGroup(channel,object:WifiP2pManager.ActionListener{
overridefunonSuccess(){
// Device is ready to accept incoming connections from peers.
}
overridefunonFailure(reason:Int){
Toast.makeText(
this@WiFiDirectActivity,
"P2P group creation failed. Retry.",
Toast.LENGTH_SHORT
).show()
}
})

Java

manager.createGroup(channel,newWifiP2pManager.ActionListener(){
@Override
publicvoidonSuccess(){
// Device is ready to accept incoming connections from peers.
}
@Override
publicvoidonFailure(intreason){
Toast.makeText(WiFiDirectActivity.this,"P2P group creation failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});

Note: If all the devices in a network support Wi-Fi Direct, you can use the connect() method on each device because the method then creates the group and selects a group owner automatically.

After you create a group, you can call requestGroupInfo() to retrieve details about the peers on the network, including device names and connection statuses.

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2026年08月14日 UTC.