我使用以下代码来获取信号强度,
SignalStrengthListener signalStrengthListener;
signalStrengthListener = new SignalStrengthListener();
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(
signalStrengthListener,
SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
然后它正在侦听信号强度,
private class SignalStrengthListener extends PhoneStateListener {
@Override
public void onSignalStrengthsChanged(
android.telephony.SignalStrength signalStrength) {
// get the signal strength (a value between 0 and 31)
int strengthAmplitude = signalStrength.getGsmSignalStrength();
// do something with it (in this case we update a text view)
// signalStrengthText.setText(String.valueOf(strengthAmplitude));
if (strengthAmplitude > 30) {
signalStrengthText.setText("Good");
// signalStrengthText.setTextColor(getResources().getColor(R.color.good));
} else if (strengthAmplitude > 20 && strengthAmplitude < 30) {
signalStrengthText.setText("Average");
// signalStrengthText.setTextColor(getResources().getColor(R.color.average));
} else if (strengthAmplitude < 20) {
signalStrengthText.setText("Weak");
// signalStrengthText.setTextColor(getResources().getColor(R.color.weak));
}
super.onSignalStrengthsChanged(signalStrength);
}
}
如果设备中存在SIM卡,则效果很好。但是当我从设备中移除SIM卡然后检查信号强度时,它仍然为信号强度提供了一些值。
我能想到的一个可能的解决方案是首先检查设备中是否存在SIM卡,然后显示信号强度。但我想知道对这种奇怪行为的解释以及可能的解决方案。
答案 0 :(得分:4)
答案 1 :(得分:0)
在检查信号强度之前,可以检查是否有SIM卡的设备(如果您担心WIFI网络,则需要单独处理),然后检查信号强度。您可以尝试
public boolean isSimAvailable() {
boolean isAvailable = false;
TelephonyManager telMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
int simState = telMgr.getSimState();
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT: //SimState = “No Sim Found!”;
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED: //SimState = “Network Locked!”;
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED: //SimState = “PIN Required to access SIM!”;
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED: //SimState = “PUK Required to access SIM!”; // Personal Unblocking Code
break;
case TelephonyManager.SIM_STATE_READY:
isAvailable = true;
break;
case TelephonyManager.SIM_STATE_UNKNOWN: //SimState = “Unknown SIM State!”;
break;
}
return isAvailable;
}
////当您获得信号强度时,请检查
SignalStrengthListener signalStrengthListener;
if(isSimAvailable()){
signalStrengthListener = new SignalStrengthListener();
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(
signalStrengthListener,
SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
} else {
//alert the user or do other stuff.
}