I registered a receiver that listens to network events:
You can also cache in a static field the last handled connection type and check against the incomming broadcasts. This way you will only get one broadcast per connection type.
When connection type gets changed it will obviously work. When device gets out of connection activeNetworkInfo
will be null and currentType
will be NO_CONNECTION_TYPE
as in default case.
public class ConnectivityReceiver extends BroadcastReceiver {
/** The absence of a connection type. */
private static final int NO_CONNECTION_TYPE = -1;
/** The last processed network type. */
private static int sLastType = NO_CONNECTION_TYPE;
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
final int currentType = activeNetworkInfo != null
? activeNetworkInfo.getType() : NO_CONNECTION_TYPE;
// Avoid handling multiple broadcasts for the same connection type
if (sLastType != currentType) {
if (activeNetworkInfo != null) {
boolean isConnectedOrConnecting = activeNetworkInfo.isConnectedOrConnecting();
boolean isWiFi = ConnectivityManager.TYPE_WIFI == currentType;
boolean isMobile = ConnectivityManager.TYPE_MOBILE == currentType;
// TODO Connected. Do your stuff!
} else {
// TODO Disconnected. Do your stuff!
}
sLastType = currentType;
}
}