Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NetworkConnection(private val context: Context) : LiveData<Boolean>() {
- private val connectionManager: ConnectivityManager =
- context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
- private var networkCallback: ConnectivityManager.NetworkCallback? = null
- override fun onActive() {
- super.onActive()
- updateConnection()
- when {
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
- connectionManager.registerDefaultNetworkCallback(connectivityManagerCallback())
- }
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
- lollipopNetwork()
- }
- else -> context.registerReceiver(
- networkReceiver,
- IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
- )
- }
- }
- override fun onInactive() {
- super.onInactive()
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- connectionManager.unregisterNetworkCallback(connectivityManagerCallback())
- } else {
- context.unregisterReceiver(networkReceiver)
- }
- }
- @TargetApi(Build.VERSION_CODES.LOLLIPOP)
- private fun lollipopNetwork() {
- val requestBuilder = NetworkRequest.Builder()
- .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
- .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
- .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
- connectionManager.registerNetworkCallback(
- requestBuilder.build(),
- connectivityManagerCallback()
- )
- }
- private fun connectivityManagerCallback() : ConnectivityManager.NetworkCallback {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- if (networkCallback == null) {
- networkCallback = object : ConnectivityManager.NetworkCallback() {
- override fun onLost(network: Network) {
- super.onLost(network)
- postValue(false)
- }
- override fun onAvailable(network: Network) {
- super.onAvailable(network)
- postValue(true)
- }
- }
- }
- return networkCallback as ConnectivityManager.NetworkCallback
- } else {
- throw IllegalAccessError("Error")
- }
- }
- private val networkReceiver = object : BroadcastReceiver() {
- override fun onReceive(context: Context?, intent: Intent?) {
- updateConnection()
- }
- }
- private fun updateConnection() {
- val activeNetwork: NetworkInfo? = connectionManager.activeNetworkInfo
- postValue(activeNetwork?.isConnected == true)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement