Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use registerNetworkCallback with PendingIntent?

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?

like image 890
vvkatwss vvkatwss Avatar asked Sep 13 '25 07:09

vvkatwss vvkatwss


1 Answers

Finally I made it works. First I need to add the receiver to AndroidManifest.xml

<receiver 
        android:name=".NetworkStateReceiver"
        android:enabled="true"
        android:exported="true" />

Second, NetworkStateReceiver#onReceive is called only once when the connection was offline and becomes available. So every-time I need to send anything when the connection is offline I have to call registerNetworkUpdates.

Third, I have to call unregisterNetworkCallback before calling registerNetworkCallback. If I called registerNetworkCallback twice with the same Intent, NetworkStateReceiver#onReceive was called twice. And I used applicationContext instead of this when creating PendingIntent.getBroadcast.

like image 59
vvkatwss vvkatwss Avatar answered Sep 15 '25 20:09

vvkatwss vvkatwss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!