问题描述
我正在尝试在 android 中使用 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()
}
}
)}
但是peer连接后,intent广播是WIFI_P2P_PEERS_CHANGED_ACTION而不是WIFI_P2P_CONNECTION_CHANGED_ACTION。在 android 版本 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
}
}
}
任何帮助将不胜感激..
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)