diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml index 0c0c338..fda3e39 100644 --- a/.idea/deploymentTargetDropDown.xml +++ b/.idea/deploymentTargetDropDown.xml @@ -3,7 +3,40 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e31d521..6780e64 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,32 @@ + + + + + + + + + + + + + + + + + + + - WidgetTaskStudent(database, taskGroup) + // Indicates a change in the Wi-Fi Direct status. + intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION) + intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION) + intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) + intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION) + + this.registerReceiver(MyBroadcastReceiver(this), intentFilter) + */ + + // get the WiFi direct manager + val manager: WifiP2pManager? = this.getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager? + if (manager == null) { + Log.e("wifi-p2p", "cannot get the manager") + return + } + + val channel = manager.initialize(this, this.mainLooper, null) + + // get the list of peers in the group + manager.requestPeers(channel) { devices -> + devices.deviceList.forEach { device -> + Log.d("wifi-p2p", "peer found : [${device.deviceAddress}] ${device.deviceName}") + } + } + + manager.requestGroupInfo(channel) { group -> + val config = WifiP2pConfig().apply { + this.deviceAddress = group.owner.deviceAddress + } + + if (group.isGroupOwner) { + // the device is the host + Log.d("wifi-p2p", "I am the owner ! (${group.owner})") + + Thread { + while (true) { + // declare the server + val serverSocket = ServerSocket() + serverSocket.bind(InetSocketAddress(8888)) + + // accept a connection + val clientSocket = serverSocket.accept() + val data = clientSocket.getInputStream().read() + + // print the data + Log.i("wifi-p2p", "Data received (${clientSocket.inetAddress}) : $data") + + // close the connection + clientSocket.close() + } + }.start() + + } else { + // the device is a simple peer + Log.d("wifi-p2p", "I am a peer !") + + // connect to the host and send a packet + Thread { + manager.connect(channel, config, object : ActionListener { + override fun onSuccess() { + val hostAddress = InetAddress.getByName(config.deviceAddress) + val port = 8888 + + Log.d("wifi-p2p", "Sending packet to host") + val socket = Socket() + socket.connect(InetSocketAddress(hostAddress, port)) + socket.outputStream.write("test".toByteArray()) + } + + override fun onFailure(reason: Int) { + Log.e("wifi-p2p", "Error when connecting to host : $reason") + } + }) } } } - */ - } + }