Last active
February 17, 2023 13:10
-
-
Save prashantwosti/e996fb5b8e4c5cd607ee5650adbecf3c to your computer and use it in GitHub Desktop.
Internet connection check using LiveData. For android version M or higher.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InternetConnectionCheck (context: Context) : LiveData<Boolean>() { | |
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
override fun onActive() { | |
super.onActive() | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { | |
connectivityManager.registerDefaultNetworkCallback(getNetworkCallback()) | |
} else { | |
connectivityManager.registerNetworkCallback(getNetworkRequest(), getNetworkCallback()) | |
} | |
} | |
override fun onInactive() { | |
super.onInactive() | |
try { | |
connectivityManager.unregisterNetworkCallback(getNetworkCallback()) | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} | |
private fun getNetworkCallback() = object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
super.onAvailable(network) | |
postValue(true) | |
} | |
override fun onLost(network: Network) { | |
super.onLost(network) | |
postValue(false) | |
} | |
} | |
private fun getNetworkRequest() = NetworkRequest.Builder() | |
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) | |
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) | |
.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET) | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) | |
.build() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
InternetConnectionCheck(this).observe(this, Observer { isConnected -> | |
if (isConnected) { | |
// do something | |
} | |
}) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyApplication : Application() { | |
override fun onCreate() { | |
super.onCreate() | |
InternetConnectionCheck(this).observeForever({ isConnected -> | |
if (isConnected) { | |
// do something | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment