下面列出了android.net.Network#getSocketFactory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static SocketFactory getWifiSocketFactory(final Context context) {
SocketFactory socketFactory = SocketFactory.getDefault();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !isGalaxyDevice()) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] allNetwork = cm.getAllNetworks();
for (Network network : allNetwork) {
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
socketFactory = network.getSocketFactory();
}
}
}
return socketFactory;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Socket createWiFiSocket(Context context) {
if(context == null){
logInfo("Context supplied was null");
return null;
}
PackageManager pm = context.getPackageManager();
if (pm == null) {
logInfo("PackageManager isn't available.");
return null;
}
// getAllNetworks() and getNetworkCapabilities() require ACCESS_NETWORK_STATE
if (pm.checkPermission(Manifest.permission.ACCESS_NETWORK_STATE, context.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
logInfo("Router service doesn't have ACCESS_NETWORK_STATE permission. It cannot bind a TCP transport to Wi-Fi network.");
return null;
}
ConnectivityManager connMan = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMan == null) {
logInfo("ConnectivityManager isn't available.");
return null;
}
Network[] allNetworks = connMan.getAllNetworks();
if (allNetworks == null) {
logInfo("Failed to acquire a list of networks.");
return null;
}
// Samsung Galaxy S9 (with Android 8.0.0) provides two `Network` instances which have
// TRANSPORT_WIFI capability. The first one throws an IOException upon creating a Socket,
// and the second one actually works. To support such case, here we iterate over all
// `Network` instances until we can create a Socket.
for (Network network : allNetworks) {
if (network == null) {
continue;
}
NetworkCapabilities capabilities = connMan.getNetworkCapabilities(network);
if (capabilities == null) {
continue;
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
try {
SocketFactory factory = network.getSocketFactory();
if (factory != null) {
return factory.createSocket();
}
} catch (IOException e) {
logInfo("IOException during socket creation (ignored): " + e.getMessage());
}
}
}
logInfo("Cannot find Wi-Fi network to bind a TCP transport.");
return null;
}