我在尝试连接到运行相同应用的多个设备时遇到问题。我的应用程序的工作流程是:
问题:在第3步中,当我调用connect方法时,代码连接到第一个设备没有任何问题,但是当它到达第二个循环迭代时连接到第二个或第三个被选中的设备因原因码2(忙)而失败。为什么会这样?当我只连接到一个设备时它一切正常,只有当我尝试连接到多个设备时才会出现问题?我究竟做错了什么?我无法找到如何连接到多个设备的任何示例...非常感谢任何帮助。
代码A :(发现同行)
private WifiP2pManager mManager;
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
onInitiateDiscovery();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(getActivity(), "Discovery Failed: " + getReascodeText(reasonCode), Toast.LENGTH_SHORT).show();
}
});
代码B :(选择要连接的对等方)
public void onPeersAvailable(WifiP2pDeviceList peers) {
final ArrayList<Integer> itemsSelected = new ArrayList<>();
// Out with the old, in with the new.
mPeers.clear();
mPeers.addAll(peers.getDeviceList());
CharSequence[] cs = StringUtils.getDeviceNames(mPeers);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Who do you want to share with?");
builder.setMultiChoiceItems(cs, null, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int selectedItemId, boolean isChecked) {
if (isChecked) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
}).setPositiveButton("Done!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
WifiP2pDevice wifiP2pDevice = mPeers.get(itemsSelected.get(0));
List<WifiP2pDevice> devices = extractSelectedDevices(itemsSelected,mPeers);
numConnections = devices.size();
connect(devices);
}
});
mPeerSelectionDialog = builder.create();
mPeerSelectionDialog.show();
}
代码C :(连接到选定的设备)
public void connect(List<WifiP2pDevice> devices) {
for(WifiP2pDevice device: devices) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
System.out.println("successfully connected!!");
Log.d(MultiImageSelectorFragment.TAG, ">>>>>>>>>>>>>>>>>>>>>!!Successfully Connected!<<<<<<<<<<<");
}
@Override
public void onFailure(int reason) {
Toast.makeText(getActivity(), "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
Log.d(MultiImageSelectorFragment.TAG, ">>>>>>>>>>>>>>>>>>>>>!!Failed connection, rasoncode:"+reason+" !<<<<<<<<<<<");
}
});
}
答案 0 :(得分:1)
这是正确的,在连接到第一个设备后,它将无法连接繁忙的错误代码。原因是您的设备上的WiFiP2P尚未完成第一个设备连接过程(即使您已接受连接并且已建立,仍需要一些时间来创建组并释放资源)。
要解决此问题,您可以启动另一个有一些延迟的线程(从我的测试起至少10-15秒)以尝试连接到第二个设备。
古德勒克。