有没有一种方法可以在代码中忘记旧的WiFi Direct连接?我需要这样做来改变谁成为组所有者。我设置groupOwnerIntent = 15,但仍然无法成为组所有者。
WiFiP2p
连接,只需调用WiFiP2pManager#removeGroup
。无论设备是GO还是peer都可以。 manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.d(TAG, "removeGroup success");
deletePersistentGroup(group);
}
@Override
public void onFailure(int reason) {
Log.d(TAG, "removeGroup fail: " + reason);
}
});
这里的manager
是WiFip2pManager
的实例。而deletePersistanteGroup(WiFiP2pGroup group)
则是:
private void deletePersistentGroup(WifiP2pGroup wifiP2pGroup) {
try {
Method getNetworkId = WifiP2pGroup.class.getMethod("getNetworkId");
Integer networkId = (Integer) getNetworkId.invoke(wifiP2pGroup);
Method deletePersistentGroup = WifiP2pManager.class.getMethod("deletePersistentGroup",
WifiP2pManager.Channel.class, int.class, WifiP2pManager.ActionListener.class);
deletePersistentGroup.invoke(manager, channel, networkId, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.e(TAG, "deletePersistentGroup onSuccess");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "deletePersistentGroup failure: " + reason);
}
});
} catch (NoSuchMethodException e) {
Log.e("WIFI", "Could not delete persistent group", e);
} catch (InvocationTargetException e) {
Log.e("WIFI", "Could not delete persistent group", e);
} catch (IllegalAccessException e) {
Log.e("WIFI", "Could not delete persistent group", e);
}
}
更新
如果想成为GO(组群拥有者),在邀请其他设备之前,你需要调用WiFiP2pManager#createGroup()
方法。