获得当前连接网络信息

In Android:

 

 ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo aNetInfo = cm.getActiveNetworkInfo();
  
  lifecycleText.append(aNetInfo.getDetailedState().toString()+";;/n"
    +aNetInfo.getExtraInfo()+";"+aNetInfo.getTypeName()+";"+aNetInfo.getSubtypeName());

 

aNetInfo.getDetailedState():连接状态 connected.

aNetInfo.getExtraInfo: apn name such as cmnet or cmwap

aNetInfo.getTypeName: MOBILE or WIFI.

aNetInfo.getSubtypeName: network type such as EDGE, or UMTS.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要获取当前连接到的网络的城市和国家,你可以使用Geolocation API和Android网络连接管理器。以下是获取当前连接到的网络城市和国家的示例代码: ``` // 检查网络连接状态 ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // 获取网络连接类型 int networkType = networkInfo.getType(); if (networkType == ConnectivityManager.TYPE_WIFI || networkType == ConnectivityManager.TYPE_MOBILE) { // 获取网络连接的IP地址 String ipAddress = getIPAddress(networkType); // 获取当前位置信息 Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocationName(ipAddress, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); String city = address.getLocality(); String country = address.getCountryName(); // 使用城市和国家信息 // ... } } } // 获取网络连接的IP地址 private String getIPAddress(int networkType) { if (networkType == ConnectivityManager.TYPE_WIFI) { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff)); } else if (networkType == ConnectivityManager.TYPE_MOBILE) { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLinkLocalAddress()) { String ipAddress = inetAddress.getHostAddress().toString(); if (ipAddress.contains(".") && !ipAddress.contains(":")) { return ipAddress; } } } } } catch (Exception e) { e.printStackTrace(); } } return null; } ``` 注意:该方法可能不是100%准确,因为IP地址可能与实际位置不同,但在大多数情况下,它应该可以提供有用的信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值