Broadcast receiver for checking internet connection in android app

后端 未结 21 3228
温柔的废话
温柔的废话 2020-11-21 22:28

I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get

21条回答
  •  遥遥无期
    2020-11-21 22:48

    Warning: Declaring a broadcastreceiver for android.net.conn.CONNECTIVITY_CHANGE is deprecated for apps targeting N and higher. In general, apps should not rely on this broadcast and instead use JobScheduler or GCMNetworkManager.

    As CONNECTIVITY_CHANGE is deprecated then we should use another way of doing the same stuff

    Following NetworkConnectionLiveData will handle all the OS Version till now and also if target SDK is less than Build.VERSION_CODES.LOLLIPOP then only we can use broadcastReceiver

    Best Part is this class uses LiveData so no need to register any receiver use LiveData and it will handle all the things

    class NetworkConnectionLiveData(val context: Context) : LiveData() {
    
        private var connectivityManager: ConnectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
    
        private lateinit var connectivityManagerCallback: ConnectivityManager.NetworkCallback
    
        override fun onActive() {
            super.onActive()
            updateConnection()
            when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> connectivityManager.registerDefaultNetworkCallback(getConnectivityManagerCallback())
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> lollipopNetworkAvailableRequest()
                else -> {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        context.registerReceiver(networkReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))
                    }
                }
            }
        }
    
        override fun onInactive() {
            super.onInactive()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                connectivityManager.unregisterNetworkCallback(connectivityManagerCallback)
            } else {
                context.unregisterReceiver(networkReceiver)
            }
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private fun lollipopNetworkAvailableRequest() {
            val builder = NetworkRequest.Builder()
                    .addTransportType(android.net.NetworkCapabilities.TRANSPORT_CELLULAR)
                    .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI)
            connectivityManager.registerNetworkCallback(builder.build(), getConnectivityManagerCallback())
        }
    
        private fun getConnectivityManagerCallback(): ConnectivityManager.NetworkCallback {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    
                connectivityManagerCallback = object : ConnectivityManager.NetworkCallback() {
                    override fun onAvailable(network: Network?) {
                        postValue(true)
                    }
    
                    override fun onLost(network: Network?) {
                        postValue(false)
                    }
                }
                return connectivityManagerCallback
            } else {
                throw IllegalAccessError("Should not happened")
            }
        }
    
        private val networkReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                updateConnection()
            }
        }
    
        private fun updateConnection() {
            val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
            postValue(activeNetwork?.isConnected == true)
        }
    } 
    

    Use of the LiveData into any class:

    NetworkConnectionLiveData(context ?: return)
        .observe(viewLifecycleOwner, Observer { isConnected ->
            if (!isConnected) {
                // Internet Not Available
                return@Observer
            }
            // Internet Available
    })
    

提交回复
热议问题