我试图在安卓系统中使用WifiP2Pmanager连接两个设备。 能够列出对等物并连接所选设备。
当选择一个对等体进行连接时,下面给出的代码片断会执行
val device = deviceArray[position]
val config = WifiP2pConfig()
config.deviceAddress = device.deviceAddress
config.wps.setup = WpsInfo.PBC
channel?.also { channel ->
manager?.connect(channel, config, object : WifiP2pManager.ActionListener {
override fun onSuccess() {
Toast.makeText(applicationContext, "Connected to " + device.deviceName, Toast.LENGTH_SHORT).show()
override fun onFailure(reason: Int) {
Toast.makeText(applicationContext, "Not Connected", Toast.LENGTH_SHORT).show()
但在对等连接后,意图广播是WIFI_P2P_PEERS_CHANGED_ACTION而不是WIFI_P2P_CONNECTION_CHANGED_ACTION。在安卓7版本的设备上进行了尝试。
我按照android中解释的所有步骤和代码进行了操作。WifiDirect .
这是我在BroadcastReceiver实现中的onReceive代码部分。
override fun onReceive(context: Context, intent: Intent) {
val action: String? = intent.action
when (action) {
WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
// Check to see if Wi-Fi is enabled and notify appropriate activity
val state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1)
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is ON", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Wifi is OFF", Toast.LENGTH_SHORT).show()
WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {
// Call WifiP2pManager.requestPeers() to get a list of current peers
if (manager != null) {
manager.requestPeers(channel, activity.peerListListener);
WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {
// Respond to new connection or disconnections
if (manager == null) {
return
if (isNetworkAvailable(context)) {
activity.connectionStatus.setText("Device Connected")
manager.requestConnectionInfo(channel, activity.connectionInfoListener)
} else {
activity.connectionStatus.setText("Device Disconnected")
WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
// Respond to this device's wifi state changing