In order to check the status, there are 2 ways:
- ServiceState constants : STATE_EMERGENCY_ONLY, STATE_IN_SERVICE, STATE_OUT_OF_SERVICE, STATE_POWER_OFF .
Those you get by calling telephonyManager.serviceState.state
.
If you wish to listen to changes you use PhoneStateListener by calling telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE)
. To unregister you call telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)
This is a good solution because it seems that even if you don't have a SIM card, you can still sometimes (in some countries) call emergency phone numbers, such as the police.
enum class PhoneServiceState {
STATE_EMERGENCY_ONLY, STATE_IN_SERVICE, STATE_OUT_OF_SERVICE, STATE_POWER_OFF, UNKNOWN;
companion object {
fun getFromValue(value: Int): PhoneServiceState = when (value) {
ServiceState.STATE_EMERGENCY_ONLY -> STATE_EMERGENCY_ONLY
ServiceState.STATE_IN_SERVICE -> STATE_IN_SERVICE
ServiceState.STATE_OUT_OF_SERVICE -> STATE_OUT_OF_SERVICE
ServiceState.STATE_POWER_OFF -> STATE_POWER_OFF
else -> UNKNOWN
}
}
}
Usage:
PhoneServiceState.getFromValue(telephonyManager!!.serviceState.state)
If it's STATE_OUT_OF_SERVICE or STATE_POWER_OFF, it means you are completely disconnected. If you have STATE_EMERGENCY_ONLY, it means you can only call emergency phone calls.
You can use subscriptionManager.activeSubscriptionInfoList
. If you get a non-empty list, I think it means you are connected:
fun hasCellConnection(context: Context): Boolean {
val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
val activeSubscriptionInfoList = subscriptionManager.activeSubscriptionInfoList
return !activeSubscriptionInfoList.isNullOrEmpty()
}