What is the correct way of checking for mobile network available (no data connection)

后端 未结 6 664
名媛妹妹
名媛妹妹 2021-02-02 15:35

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

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 16:23

    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)
    }
    

    }

提交回复
热议问题