org.robolectric.shadows.ShadowConnectivityManager Maven / Gradle / Ivy
package org.robolectric.shadows;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import org.robolectric.Shadows;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.HiddenApi;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Shadow for {@link android.net.ConnectivityManager}.
*/
@Implements(ConnectivityManager.class)
public class ShadowConnectivityManager {
private NetworkInfo activeNetworkInfo;
private boolean backgroundDataSetting;
private int networkPreference = ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
private final Map networkTypeToNetworkInfo = new HashMap<>();
public ShadowConnectivityManager() {
NetworkInfo wifi = ShadowNetworkInfo.newInstance(NetworkInfo.DetailedState.DISCONNECTED,
ConnectivityManager.TYPE_WIFI, 0, true, false);
networkTypeToNetworkInfo.put(ConnectivityManager.TYPE_WIFI, wifi);
NetworkInfo mobile = ShadowNetworkInfo.newInstance(NetworkInfo.DetailedState.CONNECTED,
ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_MOBILE_MMS, true, true);
networkTypeToNetworkInfo.put(ConnectivityManager.TYPE_MOBILE, mobile);
this.activeNetworkInfo = mobile;
}
@Implementation
public NetworkInfo getActiveNetworkInfo() {
return activeNetworkInfo;
}
@Implementation
public NetworkInfo[] getAllNetworkInfo() {
return networkTypeToNetworkInfo.values().toArray(new NetworkInfo[networkTypeToNetworkInfo.size()]);
}
@Implementation
public NetworkInfo getNetworkInfo(int networkType) {
return networkTypeToNetworkInfo.get(networkType);
}
@Implementation
public boolean getBackgroundDataSetting() {
return backgroundDataSetting;
}
@Implementation
public void setNetworkPreference(int preference) {
networkPreference = preference;
}
@Implementation
public int getNetworkPreference() {
return networkPreference;
}
/**
* Count {@link ConnectivityManager#TYPE_MOBILE} networks as metered.
* Other types will be considered unmetered.
*
* @return True if the active network is metered.
*/
@Implementation
public boolean isActiveNetworkMetered() {
if (activeNetworkInfo != null) {
return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
return false;
}
}
public void setNetworkInfo(int networkType, NetworkInfo networkInfo) {
networkTypeToNetworkInfo.put(networkType, networkInfo);
}
@HiddenApi @Implementation
public void setBackgroundDataSetting(boolean b) {
backgroundDataSetting = b;
}
public void setActiveNetworkInfo(NetworkInfo info) {
activeNetworkInfo = info;
if (info != null) {
networkTypeToNetworkInfo.put(info.getType(), info);
} else {
networkTypeToNetworkInfo.clear();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy