在Android设备上获取信号强度时,使用PhoneStateListener.LISTEN_SIGNAL_STRENGTHS和TelephonyManager#requestCellInfoUpdate返回的值可能不同。这是因为PhoneStateListener.LISTEN_SIGNAL_STRENGTHS返回当前连接的塔信号强度,而TelephonyManager#requestCellInfoUpdate返回不同基站的信号强度。
为了获得最新的信号强度值,请在onSignalStrengthsChanged回调中同时使用两个方法:
public class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
telephonyManager.requestCellInfoUpdate(getMainExecutor(), new TelephonyManager.CellInfoCallback() {
@Override
public void onCellInfo(@NonNull List cellInfo) {
for (CellInfo info : cellInfo) {
if (info instanceof CellInfoLte) {
CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
Log.d(TAG, "Lte signal strength: " + lte.getDbm());
} else if (info instanceof CellInfoGsm) {
CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
Log.d(TAG, "Gsm signal strength: " + gsm.getDbm());
}
}
}
});
}
List cellInfoList = telephonyManager.getAllCellInfo();
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
CellSignalStrengthLte lte = ((CellInfoLte) cellInfo).getCellSignalStrength();
Log.d(TAG, "Lte signal strength: " + lte.getDbm());
} else if (cellInfo instanceof CellInfoGsm) {
CellSignalStrengthGsm gsm = ((CellInfoGsm) cellInfo).getCellSignalStrength();
Log.d(TAG, "Gsm signal strength: " + gsm.getDbm());
}
}
}
}
使用TelephonyManager#getCellSignalStrengths获取多个基站的信号强度,将所有信号强度平均后将其用于更准确的信号强度测量