首页 文章

连接到WiFi时如何检测网络类型(2G / 3G / LTE)

提问于
浏览
2

我正在编写一个应用程序,我想要检测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 回答

  • 0

    问题是在API版本24和转发getNetworkType()已分为两个单独的方法:

    getDataNetworkType()

    getVoiceNetworkType()

    如果返回的类型是IWLAN,我在代码中添加了一个检查,如果是,请使用getVoiceNetworkType()代替 .

    if (tm.getNetworkType() != 18)
        return tm.getNetworkType();
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) 
        return tm.getVoiceNetworkType();
    else 
        return -1;
    
  • 1

    您可以尝试使用来自 ConnectivityManagergetAllNetworks() 来跟踪所有活动网络 .

    看这里:https://developer.android.com/reference/android/net/ConnectivityManager#getAllNetworks()

    您可以使用 getNetworkInfo() 检索特定返回网络的更多详细信息

    看这里:https://developer.android.com/reference/android/net/ConnectivityManager#getNetworkInfo(android.net.Network)

  • 0

    call this method

    public void checkNetworkType(){
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    
            if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA)) {
    
                Toast.makeText(this, "3G network type", Toast.LENGTH_LONG).show();
    
    
            } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP)) {
                Toast.makeText(this, "4G network type", Toast.LENGTH_LONG).show();
    
            } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_GPRS)) {
                Toast.makeText(this, "GPRS network type", Toast.LENGTH_LONG).show();
    
            } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE)) {
                Toast.makeText(this, "2G network type", Toast.LENGTH_LONG).show();
    
            }
        }
    

相关问题