出于项目需求,需要获取到手机信号强度。本人不才,以前都是采用toString()的方法,然后截取,得到强度,但发现很多机型都不适合。苦苦在API中搜寻,结果都不是很理想。最后在Stackoverflow上发现了一个方法,试之,发现大部分机型适合,故写成方法,以便后续需要。但此方法还不是很全面,无法保证所有机型都适合,若各位大虾有更好的方法,还望不吝赐教。
/**
* 获取手机信号强度,需添加权限 android.permission.ACCESS_COARSE_LOCATION <br>
* API要求不低于17 <br>
*
* @return 当前手机主卡信号强度,单位 dBm(-1是默认值,表示获取失败)
*/
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;
}