In my application I want to notify if a device has been lost network connection and if it's connected to a network again.
So I wrote a Broadcastreceiver like this:
class NetworkReceiver() : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (isNetworkConnected(context)) {
//do some stuff
} else {
//do smoke stuff
}
}
private fun isNetworkConnected(context: Context?): Boolean {
val connectivityManager: ConnectivityManager? = context?.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager?
if (connectivityManager != null) {
if (Build.VERSION.SDK_INT < 23) {
val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
if (networkInfo != null) {
return networkInfo.isConnected
&& networkInfo.type == ConnectivityManager.TYPE_WIFI
|| networkInfo.type == ConnectivityManager.TYPE_MOBILE
}
} else {
val network: Network? = connectivityManager.activeNetwork
if (network != null) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
return (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN))
}
}
}
return false
}
My question how can I register this broadcast receiver in my activity to trigger the NetworkReceiver when my device is connected or disconnected from the network. Which IntentFilter should I use?