get SignalStrength without Using PhoneStateListener onSignalStrengthchanged

后端 未结 4 1204
無奈伤痛
無奈伤痛 2020-12-06 15:07

does anyone know how to get the signal strength without having to call the onSignalStrengthChanged. The problem with onSignalStrengthchanged is that is it called when the s

相关标签:
4条回答
  • 2020-12-06 15:43

    There is another API in Android called CellInfo. But I am not sure whether signal strength returned by OnSignalStrengthsChanged() and CellInfo is same or not.

    https://developer.android.com/reference/android/telephony/CellSignalStrength.html

    0 讨论(0)
  • 2020-12-06 15:48

    On API level 17 only, here's some code that can be used in an Activity (or any other Context child class):

    import android.telephony.CellInfo;
    import android.telephony.CellInfoCdma;
    import android.telephony.CellInfoGsm;
    import android.telephony.CellInfoLte;
    import android.telephony.CellSignalStrengthCdma;
    import android.telephony.CellSignalStrengthGsm;
    import android.telephony.CellSignalStrengthLte;
    import android.telephony.TelephonyManager;
    
    try {
        final TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        for (final CellInfo info : tm.getAllCellInfo()) {
            if (info instanceof CellInfoGsm) {
                final CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
                // do what you need
            } else if (info instanceof CellInfoCdma) {
                final CellSignalStrengthCdma cdma = ((CellInfoCdma) info).getCellSignalStrength();
                // do what you need
            } else if (info instanceof CellInfoLte) {
                final CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
                // do what you need
            } else {
                throw new Exception("Unknown type of cell signal!");
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to obtain cell signal information", e);
    }
    

    Previous versions of Android require you to call the listener, there is no other alternative (see this link).

    Also ensure that your application contains the appropriate permissions.

    0 讨论(0)
  • 2020-12-06 15:54

    you can access SignalStrength via reflection call. Please go through the link for implementation http://blog.ajhodges.com/2013/03/reading-lte-signal-strength-rssi-in.html

    0 讨论(0)
  • 2020-12-06 15:57

    Based on Andre's answer above, in Kotlin you can use this one-liner (again API 17+):

    fun getRadioSignalLevel(): Int {
      return when (val info = telephonyManager.allCellInfo?.firstOrNull()) {
        is CellInfoLte   -> info.cellSignalStrength.level
        is CellInfoGsm   -> info.cellSignalStrength.level
        is CellInfoCdma  -> info.cellSignalStrength.level
        is CellInfoWcdma -> info.cellSignalStrength.level
        else             -> 0
      }
    }
    
    0 讨论(0)
提交回复
热议问题