CONNECTIVITY_ACTION was deprecated in API level 28 and Google advices to use registerNetworkCallback(NetworkRequest, PendingIntent).
I tried registerNetworkCallback with ConnectivityManager.NetworkCallback and it works, but I want to use PendingIntent.
What confuse me is the description of public void registerNetworkCallback(NetworkRequest request, PendingIntent operation):
The operation is an Intent broadcast that goes to a broadcast receiver that you registered with Context#registerReceiver or through the tag in an AndroidManifest.xml file
Context#registerReceiver accepts IntentFilter as an argument, while PendingIntent.getBroadcast requires Intent.
Here is my code, and NetworkStateReceiver::onReceive is not called.
private fun getNetworkIntent(): PendingIntent {
if (networkPendingIntent != null) {
return networkPendingIntent!!
}
val intent = Intent(this, NetworkStateReceiver::class.java)
networkPendingIntent = PendingIntent.getBroadcast(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
return networkPendingIntent!!
}
private fun getNetworkRequest(): NetworkRequest {
return NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build()
}
private fun registerNetworkUpdates() {
var cm =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
cm?.registerNetworkCallback(getNetworkRequest(), getNetworkIntent())
}
Why?
Should I also call Context#registerReceiver? But what action should I use with IntentFilter if CONNECTIVITY_ACTION was deprecated?