top of page
  • Writer's pictureebinesvee

Wi-Fi Direct: Discover Nearby Wi-Fi P2P devices in Kotlin.

Wi-Fi Direct is a technology that allows two devices to establish a direct wireless connection with each other without the need for a Wi-Fi network or access point. It enables devices such as smartphones, tablets, and laptops to communicate with each other directly, without the need for cables or a separate Wi-Fi network.


With Wi-Fi Direct, one device acts as a host or access point, while the other device connects to it as a client. Once connected, the two devices can share files, stream media, and use other Wi-Fi Direct-enabled features.


Wi-Fi Direct is useful in situations where a Wi-Fi network or access point is not available or when users want to establish a direct connection between devices without the need for additional equipment. It is commonly used for file sharing, gaming, and printing.


In Android, Wi-Fi Direct allows devices to connect to each other using a wireless ad-hoc network, which can provide several advantages, including:


1. No Internet Connection Required: P2P Wi-Fi Direct enables devices to communicate with each other directly without the need for an internet connection or a Wi-Fi access point, making it an ideal solution for scenarios where there is no internet connection available.


2. High-Speed Data Transfer: P2P Wi-Fi Direct allows for high-speed data transfer between two devices, which can be especially useful for transferring large files or streaming media.


3. Easy to Use: P2P Wi-Fi Direct is easy to use and can be set up quickly by simply selecting the device you want to connect to from the list of available devices in the Wi-Fi settings on your Android device.


4. Low Power Consumption: P2P Wi-Fi Direct consumes less power than other wireless technologies like Bluetooth, making it an ideal solution for scenarios where battery life is important.


5. Range: P2P Wi-Fi Direct can support a range of up to 200 meters, which is much greater than Bluetooth, making it ideal for scenarios where devices need to communicate over longer distances.


Overall, P2P Wi-Fi Direct offers several advantages for Android users, making it a useful technology for a variety of scenarios.


Although P2P Wi-Fi Direct technology offers many benefits, there are some potential drawbacks to consider, some of which are the following.


1. Compatibility: Not all Android devices support P2P Wi-Fi Direct, so it may not be possible to use this technology for communication between all devices.


2. Limited Number of Devices: P2P Wi-Fi Direct can only connect a limited number of devices, typically up to 8 devices, which can be a limitation in some scenarios.


3. Security Concerns: P2P Wi-Fi Direct connections are not encrypted by default, which means that data transmitted over this network can be intercepted by third parties. However, it is possible to enable encryption for P2P Wi-Fi Direct connections to address this issue.


4. Interference: The P2P Wi-Fi Direct connection can be affected by interference from other wireless devices, especially in crowded areas with many other wireless networks and devices nearby.


5. Network Overhead: P2P Wi-Fi Direct can consume more battery power than other wireless technologies, especially during file transfers or streaming media, which may be a concern for some users.


Overall, while P2P Wi-Fi Direct technology provides many advantages, it is important to consider its limitations and potential drawbacks before using it for communication between devices.


Here are the steps to discover nearby Wi-Fi P2P devices in Kotlin Jetpack Compose.


1. Add the required permissions to the AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2. Create a broadcast receiver class that listens for Wi-Fi Direct events.


class WiFiDirectBroadcastReceiver(private val         wifiP2pManager:WifiP2pManager, private val channel: WifiP2pManager.Channel, private val activity: Activity) : BroadcastReceiver() {
  
    override fun onReceive(context: Context?, intent: Intent?) {
        when(intent?.action) {
            WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
                // Wi-Fi Direct is enabled or disabled
            }
            WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {
                // List of available peers has changed
                wifiP2pManager.requestPeers(channel, peerListListener)
            }
            WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {
                // Wi-Fi Direct connection state has changed
            }
            WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
                // Wi-Fi Direct device details have changed
            }
        }
    }
  
    private val peerListListener = WifiP2pManager.PeerListListener { peerList ->
        // List of available peers
        val peers: MutableList<WifiP2pDevice> = ArrayList()
        peers.addAll(peerList.deviceList)
    }
}

3. Register the broadcast receiver in your activity.


val wifiP2pManager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
val channel = wifiP2pManager.initialize(this, mainLooper, null)
val intentFilter = IntentFilter().apply {
    addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)
    addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)
    addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)
    addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
}
val broadcastReceiver = WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this)
registerReceiver(broadcastReceiver, intentFilter)

4. Request a list of available peers.


wifiP2pManager.discoverPeers(channel, object : WifiP2pManager.ActionListener {
    override fun onSuccess() {
        // Discovery initiated successfully
    }
    override fun onFailure(reason: Int) {
        // Discovery failed
    }
})

5. Handle the list of available peers in the peerListListener callback.


private val peerListListener = WifiP2pManager.PeerListListener { peerList ->
    // List of available peers
    val peers: MutableList<WifiP2pDevice> = ArrayList()
    peers.addAll(peerList.deviceList)
    // Do something with the list of available peers
}

In summary, discovering nearby P2P devices in Kotlin involves adding the required permissions to the AndroidManifest.xml file, creating a broadcast receiver class that listens for Wi-Fi Direct events, registering the broadcast receiver in your activity, requesting a list of available peers, and handling the list of available peers in the peerListListener callback.


Now let's see how to display the discovered devices as a list.


6. Implement a composable function to List the discovered devices as a list.


@Composable
fun DeviceList(devices: List<WifiP2pDevice>, onDeviceClick: (WifiP2pDevice) -> Unit) {
    LazyColumn {
        items(devices) { device ->
            DeviceItem(device = device, onClick = { onDeviceClick(device) })
        }
    }
}

@Composable
fun DeviceItem(device: WifiP2pDevice, onClick: () -> Unit) {
    Surface(
        shape = RoundedCornerShape(8.dp),
        modifier = Modifier
            .padding(8.dp)
            .clickable(onClick = onClick)
    ) {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = device.deviceName)
            Text(text = device.deviceAddress)
        }
    }
}


The DeviceList function is a composable function that takes a list of WifiP2pDevice objects and a callback function to handle clicks on the devices. It uses a LazyColumn to efficiently display the list of devices as a scrolling list. For each device, it creates a DeviceItem composable function, passing in the device object and the callback function.


The DeviceItem function is a composable function that displays a single device in the list. It uses a Surface to display the device with a rounded corner shape and adds padding and a clickable modifier to make it easier to click. Inside the Surface, it displays the device's name and address using two Text composable functions.


In order to use the DeviceList function, you can simply pass in the list of WifiP2pDevice objects and a callback function to handle clicks on the devices.

val devices = remember { mutableStateListOf<WifiP2pDevice>() }

DeviceList(devices = devices, onDeviceClick = { device ->
    // Handle click on device
})

This will display the list of devices as a scrolling list, with each device displayed using the DeviceItem function. When the user clicks on a device, the onDeviceClick callback function will be called with the selected WifiP2pDevice object.

64 views0 comments

Recent Posts

See All

How to setup reverse proxy on apache2

To set up a reverse proxy to a local installation using Apache2, you need to configure the Apache Virtual Hosts to forward requests to your local server. Here's a step-by-step guide: Enable Proxy Modu

Comments


bottom of page