我有两台设备:HTC One X (Android 4.2.2) 和三星 Note N8000 (Android 4.1.2)
我需要使用 Wifi P2P 连接它们。
我以使用 Wi-Fi 创建 P2P 连接、创建广播接收器和 Wifi P2P 初始化为例。
private class WifiP2PBroadcastReceiver extends BroadcastReceiver {
public WifiP2PBroadcastReceiver() {
register();
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
logger.fine("WifiP2PBroadcastReceiver: WIFI_P2P_CONNECTION_CHANGED_ACTION " + ((state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) ? "enabled" : "disabled"));
}
else if (action.equals(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)) {
peersUpdated();
}
}
public void register() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
context.registerReceiver(this, intentFilter);
}
public void unregister() {
context.unregisterReceiver(this);
}
}
Wifi P2P初始化:
private void initWifiP2p() {
// initialization
wifiP2pManager = (WifiP2pManager) context.getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifiP2pManager.initialize(context, context.getMainLooper(), new WifiP2pManager.ChannelListener() {
@Override
public void onChannelDisconnected() {
logger.fine("onChannelDisconnected");
}
});
// peer disccovery
wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
peersUpdated();
}
@Override
public void onFailure(int reason) {
}
});
}
// method called when discoverPeers listener's onSuccess is called
private void peersUpdated() {
logger.fine("peersUpdated");
wifiP2pManager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
// print all peers
for (WifiP2pDevice device : peers.getDeviceList()) {
logger.fine("peersUpdated: " + device.deviceName + " " + device.primaryDeviceType + " " + device.deviceAddress);
}
}
});
}
在两台设备上:如果 Wifi AP 断开连接 - 没有任何反应,则不会启动 Wifi 连接。不调用带有动作 WIFI_P2P_CONNECTION_CHANGED_ACTION 的广播接收器 onReceive。我需要做什么来建立 Wifi P2P 连接?
如果设备连接到 Wifi AP,则调用 WIFI_P2P_PEERS_CHANGED_ACTION,但没有找到对等点。