我需要在API 21中获取活动网络的接口名称(例如wlan0
)。
在API 23中,我可以这样做:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
Network activeNetwork = connectivityManager.getActiveNetwork();
if (activeNetwork != null)
{
LinkProperties linkProperties = connectivityManager.getLinkProperties(activeNetwork);
String name = linkProperties.getInterfaceName();
...
}
但ConnectivityManager.getActiveNetwork()
仅适用于API 23及更高版本。
是否有与API 21兼容的可接受解决方案?
我提出了以下内容,它遍历所有网络并比较NetworkInfo.toString()
(因为通过引用或值进行比较并不起作用)。它似乎工作,但它也感觉像一个巨大的黑客:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null)
{
Network[] networks = connectivityManager.getAllNetworks();
for (Network network : networks)
{
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.toString().equals(activeNetworkInfo.toString()))
{
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
String name = linkProperties.getInterfaceName();
...
break;
}
}
}
任何建议表示赞赏。