下面列出了怎么用android.net.Network的API类实例代码及写法,或者点击链接到github查看源代码。
private void waitForSomeNetworkToConnect() throws Exception {
final SettableFuture<Void> future = SettableFuture.create();
ConnectivityManager.NetworkCallback cb =
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
NetworkInfo netInfo = connManager.getNetworkInfo(network);
if (netInfo != null && netInfo.isConnected()) {
future.set(null);
}
}
};
connManager.requestNetwork(
new NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(), cb);
try {
future.get(NETWORK_STATE_CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} finally {
connManager.unregisterNetworkCallback(cb);
}
}
@Nullable
@RequiresApi(api = VERSION_CODES.LOLLIPOP)
public Network getNetworkObjectForCurrentWifiConnection() {
// Android doesn't have any means of directly asking
// "I want the Network obj for the Wi-Fi network with SSID <foo>".
// Instead, you have to infer it based on the fact that you can only
// have one connected Wi-Fi connection at a time.
// (Update: one *regular* Wi-Fi connection, anyway. See below.)
return Funcy.findFirstMatch(
Arrays.asList(connectivityManager.getAllNetworks()),
network -> {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
return false;
}
// Don't try using the P2P Wi-Fi interfaces on recent Samsung devices
if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
}
);
}
private void requestNetwork(final int transportType) throws InterruptedException {
final NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
requestBuilder.addTransportType(transportType);
final CountDownLatch awaitingNetwork = new CountDownLatch(1); // only needs to be counted down once to release waiting threads
final ConnectivityManager cm = (ConnectivityManager) mReactContext.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.requestNetwork(requestBuilder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
currentNetwork.setNetwork(network);
awaitingNetwork.countDown(); // Stop waiting
}
@Override
public void onUnavailable() {
awaitingNetwork.countDown(); // Stop waiting
}
});
// Timeout if there the network is unreachable
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
awaitingNetwork.countDown(); // Stop waiting
}
}, 5, TimeUnit.SECONDS);
awaitingNetwork.await();
}
/**
* Returns true if the system's captive portal probe was blocked for the current default data
* network. The method will return false if the captive portal probe was not blocked, the login
* process to the captive portal has been successfully completed, or if the captive portal
* status can't be determined. Requires ACCESS_NETWORK_STATE permission. Only available on
* Android Marshmallow and later versions. Returns false on earlier versions.
*/
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static boolean getIsCaptivePortal() {
// NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL is only available on Marshmallow and
// later versions.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
ConnectivityManager connectivityManager =
(ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) return false;
Network network = connectivityManager.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
return capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
}
private static boolean isInternetConnectivityValidated(ConnectivityManager connectivityManager) {
if (Util.SDK_INT < 23) {
// TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
// levels prior to 23.
return true;
}
Network activeNetwork = connectivityManager.getActiveNetwork();
if (activeNetwork == null) {
return false;
}
NetworkCapabilities networkCapabilities =
connectivityManager.getNetworkCapabilities(activeNetwork);
boolean validated =
networkCapabilities == null
|| !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
return !validated;
}
public static int getNetWorkState() {
if (mContext == null) {
throw new UnsupportedOperationException("please use NetUtils before init it");
}
// 得到连接管理器对象
ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取所有网络连接的信息
Network[] networks = connMgr.getAllNetworks();
//通过循环将网络信息逐个取出来
for (int i = 0; i < networks.length; i++) {
//获取ConnectivityManager对象对应的NetworkInfo对象
NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
if (networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return NETWORK_MOBILE;
} else {
return NETWORK_WIFI;
}
}
}
return NETWORK_NONE;
}
private boolean updateConstraintsSatisfied(JobStatus jobStatus, Network network,
NetworkCapabilities capabilities) {
// TODO: consider matching against non-active networks
final boolean ignoreBlocked = (jobStatus.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0;
final NetworkInfo info = mConnManager.getNetworkInfoForUid(network,
jobStatus.getSourceUid(), ignoreBlocked);
final boolean connected = (info != null) && info.isConnected();
final boolean satisfied = isSatisfied(jobStatus, network, capabilities, mConstants);
final boolean changed = jobStatus
.setConnectivityConstraintSatisfied(connected && satisfied);
// Pass along the evaluated network for job to use; prevents race
// conditions as default routes change over time, and opens the door to
// using non-default routes.
jobStatus.network = network;
if (DEBUG) {
Slog.i(TAG, "Connectivity " + (changed ? "CHANGED" : "unchanged")
+ " for " + jobStatus + ": connected=" + connected
+ " satisfied=" + satisfied);
}
return changed;
}
@Override
public void process(final StateMachineConnection sm) {
// Workaround when there is a data connection more than the wifi one
// http://stackoverflow.com/questions/33237074/request-over-wifi-on-android-m
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = (ConnectivityManager)
sm.mApplication.getSystemService(Context.CONNECTIVITY_SERVICE);
for (Network net : connectivityManager.getAllNetworks()) {
NetworkInfo netInfo = connectivityManager.getNetworkInfo(net);
if (netInfo != null
&& netInfo.getType() == ConnectivityManager.TYPE_WIFI
&& netInfo.getExtraInfo() != null
&& netInfo.getExtraInfo()
.equals(sm.mStateRegistry.wifiInfo.getSSID())) {
connectivityManager.bindProcessToNetwork(net);
break;
}
}
}
sm.mStateRegistry.apiAttempts = 1;
sm.setCurrentState(State.CHECK_API);
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
Network[] networks = cm.getAllNetworks();
if (networks == null)
return false;
for (Network network : networks) {
ni = cm.getNetworkInfo(network);
if (ni != null && ni.getType() != ConnectivityManager.TYPE_VPN && ni.isConnected())
return true;
}
return false;
}
/**
* Returns connection type for |network|.
* Only callable on Lollipop and newer releases.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@ConnectionType
int getConnectionType(Network network) {
NetworkInfo networkInfo = getNetworkInfo(network);
if (networkInfo != null && networkInfo.getType() == TYPE_VPN) {
// When a VPN is in place the underlying network type can be queried via
// getActiveNeworkInfo() thanks to
// https://android.googlesource.com/platform/frameworks/base/+/d6a7980d
networkInfo = mConnectivityManager.getActiveNetworkInfo();
}
if (networkInfo != null && networkInfo.isConnected()) {
return convertToConnectionType(networkInfo.getType(), networkInfo.getSubtype());
}
return ConnectionType.CONNECTION_NONE;
}
private void setUpstreamNetworkState(NetworkState ns) {
if (ns == null) {
mUpstreamNetworkState = null;
} else {
// Make a deep copy of the parts we need.
mUpstreamNetworkState = new NetworkState(
null,
new LinkProperties(ns.linkProperties),
new NetworkCapabilities(ns.networkCapabilities),
new Network(ns.network),
null,
null);
}
mLog.log("setUpstreamNetworkState: " + toDebugString(mUpstreamNetworkState));
}
private void handleLinkProp(Network network, LinkProperties newLp) {
final NetworkState prev = mNetworkMap.get(network);
if (prev == null || newLp.equals(prev.linkProperties)) {
// Ignore notifications about networks for which we have not yet
// received onAvailable() (should never happen) and any duplicate
// notifications (e.g. matching more than one of our callbacks).
return;
}
if (VDBG) {
Log.d(TAG, String.format("EVENT_ON_LINKPROPERTIES for %s: %s",
network, newLp));
}
mNetworkMap.put(network, new NetworkState(
null, newLp, prev.networkCapabilities, network, null, null));
// TODO: If sufficient information is available to select a more
// preferable upstream, do so now and notify the target.
notifyTarget(EVENT_ON_LINKPROPERTIES, network);
}
static boolean vpnActive(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
try {
for (Network network : cm.getAllNetworks()) {
NetworkCapabilities caps = cm.getNetworkCapabilities(network);
if (caps != null && caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN))
return true;
}
} catch (Throwable ex) {
Log.w(ex);
}
return false;
}
private void updateState(Network network, NetworkCapabilities capabilities) {
ConnectionHelper.NetworkState ns = ConnectionHelper.getNetworkState(ServiceSynchronize.this);
liveNetworkState.postValue(ns);
if (lastSuitable == null || lastSuitable != ns.isSuitable()) {
lastSuitable = ns.isSuitable();
EntityLog.log(ServiceSynchronize.this,
"Updated network=" + network +
" capabilities " + capabilities +
" suitable=" + lastSuitable);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
boolean background_service = prefs.getBoolean("background_service", false);
if (!background_service)
try {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(Helper.NOTIFICATION_SYNCHRONIZE, getNotificationService(lastAccounts, lastOperations).build());
} catch (Throwable ex) {
Log.w(ex);
}
}
}
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
appendLog(context, TAG, "onAvailable, network=", network, ", wasOffline=", wasOffline);
if (networkIsOffline()) {
appendLog(context, TAG, "network is offline");
wasOffline = true;
return;
}
appendLog(context, TAG, "network is online, wasOffline=", wasOffline);
if (wasOffline) {
checkAndUpdateWeather();
}
wasOffline = false;
}
void initializeVpnInPlace() {
final Network[] networks = getAllNetworksFiltered(mConnectivityManagerDelegate, null);
mVpnInPlace = null;
// If the filtered list of networks contains just a VPN, then that VPN is in place.
if (networks.length == 1) {
final NetworkCapabilities capabilities =
mConnectivityManagerDelegate.getNetworkCapabilities(networks[0]);
if (capabilities != null && capabilities.hasTransport(TRANSPORT_VPN)) {
mVpnInPlace = networks[0];
}
}
}
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
if (!network.toString().equals(mLastConnectedStatus)) {
mLastConnectedStatus = network.toString();
VpnStatus.logDebug("Connected to " + mLastConnectedStatus);
}
}
@Override
public void onAvailable(@NonNull Network network) {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getNetworkInfo(network);
EntityLog.log(ServiceSynchronize.this, "Available network=" + network + " info=" + ni);
} catch (Throwable ex) {
Log.w(ex);
}
updateState(network, null);
}
private static List<NetworkInfoModel> extractNetworkInfo(DeviceInfoHelper deviceInfoHelper) {
List<NetworkInfoModel> result = new ArrayList<>();
for (Network network : deviceInfoHelper.getNetworks()) {
NetworkInfoModel resultItem = new NetworkInfoModel();
NetworkInfo networkInfo = deviceInfoHelper.extractInfo(network);
if (networkInfo != null) {
resultItem.type = networkInfo.getType();
resultItem.typeName = networkInfo.getTypeName();
resultItem.subtype = networkInfo.getSubtype();
resultItem.subtypeName = networkInfo.getSubtypeName();
resultItem.isConnected = networkInfo.isConnected();
resultItem.detailedState = networkInfo.getDetailedState().name();
resultItem.state = networkInfo.getState().name();
resultItem.extraInfo = networkInfo.getExtraInfo();
resultItem.isAvailable = networkInfo.isAvailable();
resultItem.isFailover = networkInfo.isFailover();
resultItem.isRoaming = networkInfo.isRoaming();
}
NetworkCapabilities networkCaps = deviceInfoHelper.extractCapabilities(network);
NetworkCapabilitiesModel caps = new NetworkCapabilitiesModel();
if (networkCaps != null) {
caps.transportTypes = DeviceInfoHelper.extractTransportTypes(networkCaps);
caps.networkCapabilities = DeviceInfoHelper.extractCapNames(networkCaps);
caps.linkUpstreamBandwidthKbps = networkCaps.getLinkUpstreamBandwidthKbps();
caps.linkDownBandwidthKbps = networkCaps.getLinkDownstreamBandwidthKbps();
caps.signalStrength = extractSafeValue("mSignalStrength", networkCaps);
caps.SSID = extractSafeValue("mSSID", networkCaps);
}
resultItem.capabilities = networkCaps == null ? null : caps;
if (networkInfo != null || networkCaps != null) {
result.add(resultItem);
}
}
return result;
}
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
if (!network.toString().equals(mLastConnectedStatus)) {
mLastConnectedStatus = network.toString();
VpnStatus.logDebug("Connected to " + mLastConnectedStatus);
}
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
// A capabilities change may indicate the ConnectionType has changed,
// so forward the new NetworkInformation along to the observer.
Logging.d(TAG, "capabilities changed: " + networkCapabilities.toString());
onNetworkChanged(network);
}
@Override
public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
// A link property change may indicate the IP address changes.
// so forward the new NetworkInformation to the observer.
Logging.d(TAG, "link properties changed: " + linkProperties.toString());
onNetworkChanged(network);
}
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Network net=cm.getActiveNetwork();
if(net==null)
return null;
LinkProperties props=cm.getLinkProperties(net);
if(props==null)
return null;
return props.getInterfaceName();
}
/**
* Returns all connected networks.
* Only callable on Lollipop and newer releases.
*/
@SuppressLint("NewApi")
Network[] getAllNetworks() {
if (connectivityManager == null) {
return new Network[0];
}
return connectivityManager.getAllNetworks();
}
/**
* Returns the NetID of the current default network. Returns
* INVALID_NET_ID if no current default network connected.
* Only callable on Lollipop and newer releases.
*/
@SuppressLint("NewApi")
long getDefaultNetId() {
if (!supportNetworkCallback()) {
return INVALID_NET_ID;
}
// Android Lollipop had no API to get the default network; only an
// API to return the NetworkInfo for the default network. To
// determine the default network one can find the network with
// type matching that of the default network.
final NetworkInfo defaultNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (defaultNetworkInfo == null) {
return INVALID_NET_ID;
}
final Network[] networks = getAllNetworks();
long defaultNetId = INVALID_NET_ID;
for (Network network : networks) {
if (!hasInternetCapability(network)) {
continue;
}
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo != null && networkInfo.getType() == defaultNetworkInfo.getType()) {
// There should not be multiple connected networks of the
// same type. At least as of Android Marshmallow this is
// not supported. If this becomes supported this assertion
// may trigger. At that point we could consider using
// ConnectivityManager.getDefaultNetwork() though this
// may give confusing results with VPNs and is only
// available with Android Marshmallow.
if (defaultNetId != INVALID_NET_ID) {
throw new RuntimeException(
"Multiple connected networks of same type are not supported.");
}
defaultNetId = networkToNetId(network);
}
}
return defaultNetId;
}
/**
* Extracts NetID of Network on Lollipop and NetworkHandle (which is munged NetID) on
* Marshmallow and newer releases. Only available on Lollipop and newer releases.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@VisibleForTesting
static long networkToNetId(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return ApiHelperForM.getNetworkHandle(network);
} else {
// NOTE(pauljensen): This depends on Android framework implementation details. These
// details cannot change because Lollipop is long since released.
// NetIDs are only 16-bit so use parseInt. This function returns a long because
// getNetworkHandle() returns a long.
return Integer.parseInt(network.toString());
}
}
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
if (!network.toString().equals(mLastConnectedStatus)) {
mLastConnectedStatus = network.toString();
VpnStatus.logDebug("Connected to " + mLastConnectedStatus);
}
}
@Override
public void onLost(@NonNull Network network) {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ani = cm.getActiveNetworkInfo();
EntityLog.log(ServiceSynchronize.this, "Lost network=" + network + " active=" + ani);
if (ani == null)
lastLost = new Date().getTime();
} catch (Throwable ex) {
Log.w(ex);
}
updateState(network, null);
}
private boolean isNetworkHighBandwidth() {
Network network = mConnectivityManager.getBoundNetworkForProcess();
network = network == null ? mConnectivityManager.getActiveNetwork() : network;
if (network == null) {
return false;
}
// requires android.permission.ACCESS_NETWORK_STATE
int bandwidth = mConnectivityManager
.getNetworkCapabilities(network).getLinkDownstreamBandwidthKbps();
return bandwidth >= MIN_NETWORK_BANDWIDTH_KBPS;
}
@RequiresApi(Build.VERSION_CODES.Q)
private static boolean connectAndroidQ(@Nullable ConnectivityManager connectivityManager, @NonNull ScanResult scanResult, @NonNull String password) {
if (connectivityManager == null) {
return false;
}
WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
.setSsid(scanResult.SSID)
.setBssid(MacAddress.fromString(scanResult.BSSID));
final String security = ConfigSecurities.getSecurity(scanResult);
ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, password);
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
.build();
// not sure, if this is needed
if (networkCallback != null) {
connectivityManager.unregisterNetworkCallback(networkCallback);
}
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
wifiLog("AndroidQ+ connected to wifi ");
// bind so all api calls are performed over this new network
connectivityManager.bindProcessToNetwork(network);
}
@Override
public void onUnavailable() {
super.onUnavailable();
wifiLog("AndroidQ+ could not connect to wifi");
}
};
connectivityManager.requestNetwork(networkRequest, networkCallback);
return true;
}