dumamilk
dumamilk

Reputation: 2153

Get a "callback" for (loss of) connectivity change in a Service

Specifics: I have a service that runs the notification cast controls (CastCompanionLibrary). When I lose connection, the cast manager doesn't try to tear down the service quick enough. So if the user sleeps the device within a couple seconds of connectivity loss, the notification doesn't get taken down.

General Question: How can I get a callback/alert of a connectivity change in a Service?

Upvotes: 3

Views: 62

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 200010

You can programmatically create a BroadcastReceiver in your Service that listens for the ConnectivityManager.CONNECTIVITY_ACTION action, calling registerReceiver() when you want to start listening (say, in onCreate() or when you show the notification you eventually want to hide), then calling unregisterReceiver() when you want to stop listening (such as in onDestroy() or when you remove the notification).

You can then retrieve the connectivity by using code such as

boolean isDisconnected = intent.getBooleanExtra(
            ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

in your onReceive() method.

Upvotes: 3

Related Questions