在“ WIFI_P2P_PEERS_CHANGED_ACTION”内部被调用,WifiP2pManager.requestPeers()被调用。这将触发onPeersAvailable。在这里,每个Distinguis Peer都在for循环上找到并添加到ListView。单击listview的元素时,将调用connectToPeer。此处WifiP2pManager.connect失败,并显示“ connectToPeer Failure”。
ArrayList<ViewHolder> arrayOfUsers = new ArrayList<ViewHolder>();
mAdapter = new UsersAdapter(mActivity, arrayOfUsers);
ListView listView = (ListView) mActivity.findViewById(R.id.mobile_list);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewHolder entry= (ViewHolder) parent.getAdapter().getItem(position);
mAddress = entry.deviceAddress;
mDeviceName =entry.deviceName;
Toast.makeText(mContext, mAddress, Toast.LENGTH_SHORT).show();
connectToPeer (mAddress);//AAAAAAAAAAAAAAAAAAA
}});
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for ( WifiP2pDevice device: peers.getDeviceList()) {
mAdapter.add(new ViewHolder(device.deviceAddress,device.deviceName));
Toast.makeText(mContext, device.deviceAddress, Toast.LENGTH_SHORT).show();
//connectToPeer (device.deviceAddress);//BBBBBBBBBBBBBBBBBBBBBBBB
}
}
private void connectToPeer (String deviceAddress/*WifiP2pDevice device*/)
{
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = deviceAddress;
config.wps.setup = WpsInfo.PBC;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
Toast.makeText(mContext, "connectToPeer Successful", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reason) {
Toast.makeText(mContext, "connectToPeer Failure", Toast.LENGTH_SHORT).show();
}
});
}
如果我评论AAAAAAAAAAAAAAAAAAAAAA和未接线路BBBBBBBBBBBBBBBBBBBBB,则一部电话成功,有时另一部电话失败,并且一次又一次发现同一对等设备。 也有什么问题
else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Connection state changed! We should probably do something about
// that.
Toast.makeText(mContext, "WIFI_P2P_CONNECTION_CHANGED_ACTION", Toast.LENGTH_SHORT).show();
if (mManager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// We are connected with the other device, request connection
// info to find group owner IP
mManager.requestConnectionInfo(mChannel, this);
}