如何通过android代码获取LTE信息?

时间:2021-09-23 05:43:58

最近为了成功得到LTE的信号强度,尝试了很多种方法:

(1)通过解析signalstrength字符串,但是不同手机设备获得的字符串排列顺序不同,代码如下:

private PhoneStateListener phoneStateListener = new PhoneStateListener()
   {
             public void onSignalStrengthsChanged(SignalStrength ss)
           {
             super.onSignalStrengthsChanged(ss);
             signalinformation = ss.toString();
             signalStrength = ss.getGsmSignalStrength();
             String [] lte = signalinformation.split(" ");
             mLteSignalStrength = lte[11];
            }

}

(2)api>17时,使用cellInforLte,我获得的返回值一直是空的,代码如下:

public int getMobileDbm(Context context)
{
int dbm = -1;
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> cellInfoList;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
cellInfoList = tm.getAllCellInfo();
if (null != cellInfoList)
{
for (CellInfo cellInfo : cellInfoList)
{
if (cellInfo instanceof CellInfoGsm)
{
CellSignalStrengthGsm cellSignalStrengthGsm = ((CellInfoGsm)cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthGsm.getDbm();
}
else if (cellInfo instanceof CellInfoCdma)
{
CellSignalStrengthCdma cellSignalStrengthCdma =
((CellInfoCdma)cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthCdma.getDbm();
}
else if (cellInfo instanceof CellInfoWcdma)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
CellSignalStrengthWcdma cellSignalStrengthWcdma =
((CellInfoWcdma)cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthWcdma.getDbm();
}
}
else if (cellInfo instanceof CellInfoLte)
{
CellSignalStrengthLte cellSignalStrengthLte = ((CellInfoLte)cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthLte.getDbm();
}
}
}
}
return dbm;
}

(3)第三种方法适用于大多数设备,直接上代码:

private class SignalStrengthListener extends PhoneStateListener
{
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);

try {
lte_sinr = (Integer) signalStrength.getClass().getMethod("getLteSignalStrength").invoke(signalStrength);
lte_rsrp = (Integer) signalStrength.getClass().getMethod("getLteRsrp").invoke(signalStrength);
lte_rsrq = (Integer) signalStrength.getClass().getMethod("getLteRsrq").invoke(signalStrength);
lte_rssnr = (Integer) signalStrength.getClass().getMethod("getLteRssnr").invoke(signalStrength);
lte_cqi = (Integer) signalStrength.getClass().getMethod("getLteCqi").invoke(signalStrength);
} catch (Exception e) {
e.printStackTrace();
return;
}
}