What is the correct way of checking if a mobile network (GSM) connection is available on Android? (>2.1) I don\'t want to check if there is data connection available over the mo
I was looking during a long time for an effective solution to know if devices has access to a mobile network (not data network).
Viktor's answer is a very effective solution : https://stackoverflow.com/a/6760761/11024162
If you only want service state at a precise moment, you can unregister listener in onServiceStateChanged callback. Like this :
private inner class PhoneListener : PhoneStateListener(){
override fun onServiceStateChanged(serviceState: ServiceState?) {
if (serviceState?.state != ServiceState.STATE_IN_SERVICE) {
//Behavior when no mobile network
}
//unregister listener after one callback call
//phoneListener is the PhoneListener you previously create to register listener
val tel = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
tel.listen(phoneListener, PhoneStateListener.LISTEN_NONE)
}
}