我正在编写一个应用程序,我想要检测Android设备当前连接的网络类型(2G,3G或LTE) . 我尝试过使用以下解决方案:
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
tm.getNetworkType()
和Connectivitymanager:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getSubtype()
两种方法在没有WiFi连接的情况下工作正常但如果连接到WiFI TelephonyManager返回https://developer.android.com/reference/android/telephony/TelephonyManager#NETWORK_TYPE_IWLAN并且ConnectivityManager返回0(UNKNOWN) .
有没有办法找出手机是否连接到2G,3G或LTE,即使它连接到WiFi网络?
3 回答
问题是在API版本24和转发getNetworkType()已分为两个单独的方法:
getDataNetworkType()
和
getVoiceNetworkType()
如果返回的类型是IWLAN,我在代码中添加了一个检查,如果是,请使用getVoiceNetworkType()代替 .
您可以尝试使用来自
ConnectivityManager
的getAllNetworks()
来跟踪所有活动网络 .看这里:https://developer.android.com/reference/android/net/ConnectivityManager#getAllNetworks()
您可以使用
getNetworkInfo()
检索特定返回网络的更多详细信息看这里:https://developer.android.com/reference/android/net/ConnectivityManager#getNetworkInfo(android.net.Network)
call this method