我需要它用于 API 22 及更高版本。我看到我们有telephonyManager.getServiceState
- 但我不知道如何为 sim1 和 sim2 获得它。我们也有 CellInfo.serviceState - 但它仅来自 API 28。
如何得到它?我不需要任何听众,我只想在特定时间获取服务状态
请帮忙!
经过一些研究,实施了这个解决方案:
@SuppressLint("MissingPermission", "NewApi")
private fun getServiceState(simSlotNmb: Int): String {
try {
val serviceState: ServiceState?
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
serviceState = if (subscriptionManager != null && subscriptionManager!!.activeSubscriptionInfoCount > 1) {
val subsId =
subscriptionManager!!.getActiveSubscriptionInfoForSimSlotIndex(
simSlotNmb
).subscriptionId
val telephonyManager =
(context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager)
.createForSubscriptionId(subsId)
telephonyManager.serviceState
} else {
telephonyManager.serviceState
}
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && subscriptionManager != null
&& subscriptionManager!!.activeSubscriptionInfoCount > 1) {
val subsId = subscriptionManager!!.getActiveSubscriptionInfoForSimSlotIndex(simSlotNmb).subscriptionId
val telephonyManagerForSlot
= (context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager)
.createForSubscriptionId(subsId)
telephonyManagerForSlot.listen(phoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE)
telephonyManagerForSlot.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)
serviceState = latestServiceState
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && subscriptionManager != null
&& subscriptionManager!!.activeSubscriptionInfoCount > 1) {
val noConnectionDbm = -110
val dbm = getSignalDbm(simSlotNmb)
serviceState = ServiceState()
if(dbm < noConnectionDbm) {
serviceState.state = ServiceState.STATE_OUT_OF_SERVICE
} else {
serviceState.state = ServiceState.STATE_IN_SERVICE
}
} else {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE)
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)
serviceState = latestServiceState
}
return when (serviceState?.state) {
ServiceState.STATE_IN_SERVICE -> "in service"
ServiceState.STATE_EMERGENCY_ONLY -> "emergency only"
else -> "out of service"
}
} catch (exc: Exception) {
exc.printStackTrace()
return when(exc) {
is ArrayIndexOutOfBoundsException -> "out of service"
else -> Constants.error
}
}
}