在你的AndroidManifest.xml 文件
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
您的代碼:
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Service.CONNECTIVITY_SERVICE);
/* you can print your active network via using below */
Log.i("myNetworkType: ", connectivityManager.getActiveNetworkInfo().getTypeName());
WifiManager wifiManager= (WifiManager) getApplicationContext().getSystemService(getApplicationContext().WIFI_SERVICE);
Log.i("routes ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getRoutes().toString());
Log.i("domains ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDomains().toString());
Log.i("ip address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getLinkAddresses().toString());
Log.i("dns address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDnsServers().toString());
if(connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
Log.i("myType ", "wifi");
DhcpInfo d =wifiManager.getDhcpInfo();
Log.i("info", d.toString()+"");
}
else if(connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET) {
/* there is no EthernetManager class, there is only WifiManager. so, I used this below trick to get my IP range, dns, gateway address etc */
Log.i("myType ", "Ethernet");
Log.i("routes ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getRoutes().toString());
Log.i("domains ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDomains().toString());
Log.i("ip address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getLinkAddresses().toString());
Log.i("dns address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDnsServers().toString());
}
else {
}
輸出
不能達到知道你是否是通過WiFi或網絡使用WifiManager
爲WifiManager
只帶wifi連接交易。您必須使用ConnectivityManager
。我再次更新了代碼WifiManager
和ConnectivityManager
以生成您想要的結果。
但你知道如何獲取網關/路由器的IP地址,網絡掩碼,DNS設置時,設備通過以太網連接? 。 – widhaprasa
@WidhaprasaWaliprana connectivityManager.getActiveNetworkInfo()的toString() –
我得到: [類型:Ethernet [],狀態:連接/連接,原因:(未指定),額外:(無),漫遊:假故障轉移:假,isAvailable:true,isConnectedToProvisioningNetwork:false] 我沒有得到網關/路由器的ip地址,網絡掩碼,dns – widhaprasa