我有这个功能。但我在这一行遇到错误:|
int nrState = regInfo.getNrState();
留言:
无法解析“NetworkRegistrationInfo”中的“getNrState”方法
有人可以告诉我我犯错了吗?或者我应该以不同的方式做到这一点?
ServiceState serviceState = telephonyManager.getServiceState();
if (serviceState != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
for (NetworkRegistrationInfo regInfo : serviceState.getNetworkRegistrationInfoList()) {
if (regInfo.getAccessNetworkTechnology() == TelephonyManager.NETWORK_TYPE_NR) {
int nrState = regInfo.getNrState(); // 👈
switch (nrState) {
case NetworkRegistrationInfo.NR_STATE_NONE:
return "Not in NR state";
case NetworkRegistrationInfo.NR_STATE_RESTRICTED:
return "Restricted NR state";
case NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED:
return "Non-restricted NR state";
case NetworkRegistrationInfo.NR_STATE_CONNECTED:
return "Connected to 5G NR";
}
}
}
}
}
我需要访问每张 SIM 卡的 getNrState()。
您面临的问题是因为
getNrState()
是在 API 29 中引入的。如果您使用低于此 API 级别的任何设备或模拟器,则该功能不可用。此外,许多设备可能没有完整的 5G 支持,因此该方法在某些设备中无法识别。
您可以执行以下操作:
ServiceState serviceState = telephonyManager.getServiceState();
if (serviceState != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Ensure Android 11 or higher
List<NetworkRegistrationInfo> regInfoList = serviceState.getNetworkRegistrationInfoList();
if (regInfoList != null) {
for (NetworkRegistrationInfo regInfo : regInfoList) {
if (regInfo.getAccessNetworkTechnology() == TelephonyManager.NETWORK_TYPE_NR) {
// Ensure API level compatibility for getNrState()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
int nrState = regInfo.getNrState(); // Only available on API 29+switch (nrState) {
case NetworkRegistrationInfo.NR_STATE_NONE:
return "Not in NR state";
case NetworkRegistrationInfo.NR_STATE_RESTRICTED:
return "Restricted NR state";
case NetworkRegistrationInfo.NR_STATE_NOT_RESTRICTED:
return "Non-restricted NR state";
case NetworkRegistrationInfo.NR_STATE_CONNECTED:
return "Connected to 5G NR";
}
} else {
return "getNrState() not available on this Android version";
}
}
}
}
}
}