下面列出了怎么用android.net.NetworkCapabilities的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCapabilitiesChanged(
Network network, NetworkCapabilities networkCapabilities) {
if (ignoreConnectedNetwork(network, networkCapabilities)) {
return;
}
// A capabilities change may indicate the ConnectionType has changed,
// so forward the new ConnectionType along to observer.
final long netId = networkToNetId(network);
final int connectionType = mConnectivityManagerDelegate.getConnectionType(network);
runOnThread(new Runnable() {
@Override
public void run() {
mObserver.onNetworkConnect(netId, connectionType);
}
});
}
@SuppressWarnings("unused")
private static boolean isRelaxedSatisfied(JobStatus jobStatus, Network network,
NetworkCapabilities capabilities, Constants constants) {
// Only consider doing this for prefetching jobs
if (!jobStatus.getJob().isPrefetch()) {
return false;
}
// See if we match after relaxing any unmetered request
final NetworkCapabilities relaxed = new NetworkCapabilities(
jobStatus.getJob().getRequiredNetwork().networkCapabilities)
.removeCapability(NET_CAPABILITY_NOT_METERED);
if (relaxed.satisfiedByNetworkCapabilities(capabilities)) {
// TODO: treat this as "maybe" response; need to check quotas
return jobStatus.getFractionRunTime() > constants.CONN_PREFETCH_RELAX_FRAC;
} else {
return false;
}
}
@VisibleForTesting
static boolean isSatisfied(JobStatus jobStatus, Network network,
NetworkCapabilities capabilities, Constants constants) {
// Zeroth, we gotta have a network to think about being satisfied
if (network == null || capabilities == null) return false;
// First, are we insane?
if (isInsane(jobStatus, network, capabilities, constants)) return false;
// Second, is the network congested?
if (isCongestionDelayed(jobStatus, network, capabilities, constants)) return false;
// Third, is the network a strict match?
if (isStrictSatisfied(jobStatus, network, capabilities, constants)) return true;
// Third, is the network a relaxed match?
if (isRelaxedSatisfied(jobStatus, network, capabilities, constants)) return true;
return false;
}
private void request(final CheckNetResponse checkNetResponse) {
finishCount = 0;
errCount = 0;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
checkNetResponse.sendFinishMessage(0, "无法连接到睿思,请打开网络连接");
} //else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
checkSchoolNet(context);
checkOutNet(context);
} else {
final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
checkSchoolNet(context);
checkOutNet(context);
} else {
checkNetResponse.sendFinishMessage(0, "无法连接到睿思,请打开网络连接");
}
}
}
private void handleRequestSuplConnection(InetAddress address) {
if (DEBUG) {
String message = String.format(
"requestSuplConnection, state=%s, address=%s",
agpsDataConnStateAsString(),
address);
Log.d(TAG, message);
}
if (mAGpsDataConnectionState != AGPS_DATA_CONNECTION_CLOSED) {
return;
}
mAGpsDataConnectionIpAddr = address;
mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPENING;
NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
requestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
NetworkRequest request = requestBuilder.build();
mConnMgr.requestNetwork(
request,
mSuplConnectivityCallback);
}
/**
* Updates {@link #mNetworkCapabilities} based on current underlying networks and returns a
* defensive copy.
*
* <p>Does not propagate updated capabilities to apps.
*
* @param defaultNetwork underlying network for VPNs following platform's default
*/
public synchronized NetworkCapabilities updateCapabilities(
@Nullable Network defaultNetwork) {
if (mConfig == null) {
// VPN is not running.
return null;
}
Network[] underlyingNetworks = mConfig.underlyingNetworks;
if (underlyingNetworks == null && defaultNetwork != null) {
// null underlying networks means to track the default.
underlyingNetworks = new Network[] { defaultNetwork };
}
applyUnderlyingCapabilities(
mContext.getSystemService(ConnectivityManager.class),
underlyingNetworks,
mNetworkCapabilities);
return new NetworkCapabilities(mNetworkCapabilities);
}
/**
* 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 = ApiHelperForM.getActiveNetwork(connectivityManager);
if (network == null) return false;
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
return capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
}
public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
this.messenger = messenger;
asyncChannel = ac;
network = net;
networkInfo = info;
linkProperties = lp;
networkCapabilities = nc;
currentScore = score;
mConnService = connService;
mContext = context;
mHandler = handler;
networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
networkMisc = misc;
}
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;
}
@Override
public String toString() {
StringJoiner j = new StringJoiner(", ", "DefaultNetworkEvent(", ")");
j.add("netId=" + netId);
for (int t : BitUtils.unpackBits(transports)) {
j.add(NetworkCapabilities.transportNameOf(t));
}
j.add("ip=" + ipSupport());
if (initialScore > 0) {
j.add("initial_score=" + initialScore);
}
if (finalScore > 0) {
j.add("final_score=" + finalScore);
}
j.add(String.format("duration=%.0fs", durationMs / 1000.0));
j.add(String.format("validation=%04.1f%%", (validatedMs * 100.0) / durationMs));
return j.toString();
}
@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);
}
);
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isWifiNetworkReachable(
@NonNull final NetworkCapabilities capabilities,
@NonNull final NetworkInfo info) {
final boolean isWiFi;
if (BuildCheck.isAPI26()) {
isWiFi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) // API>=21
|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET); // API>=21
// || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE); // API>=26 これはWi-Fi端末間での近接情報の発見機能
} else {
isWiFi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) // API>=21
|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET); // API>=21
}
return isWiFi && isNetworkReachable(capabilities, info);
}
@Override
public void onCapabilitiesChanged(
Network network, NetworkCapabilities networkCapabilities) {
if (ignoreConnectedNetwork(network, networkCapabilities)) {
return;
}
// A capabilities change may indicate the ConnectionType has changed,
// so forward the new ConnectionType along to observer.
final long netId = networkToNetId(network);
final int connectionType = mConnectivityManagerDelegate.getConnectionType(network);
runOnThread(new Runnable() {
@Override
public void run() {
mObserver.onNetworkConnect(netId, connectionType);
}
});
}
private String findLocalIp1(){
ConnectivityManager connMgr = (ConnectivityManager) IApplication.get_context().getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && connMgr != null) {
LinkProperties linkProperties;
String ipAddress = null;
linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_VPN);
if (linkProperties == null)
linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_ETHERNET);
if (linkProperties == null)
linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_WIFI);
if (linkProperties != null)
ipAddress = getIp(linkProperties);
if (ipAddress != null)
return ipAddress;
}
return null;
}
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];
}
}
}
public void testSocketFactoryNull2() {
setupMockNetworks(new MockNetworkConfig[] {
new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_CELLULAR, FactoryRet.RETURNS_ANOTHER_FACTORY),
new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_NULL),
new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_CORRECT_FACTORY),
});
Socket ret = WiFiSocketFactory.createSocket(mMockContext);
assertNotNull("createSocket() should always return a Socket instance", ret);
assertEquals("Returned Socket should be created through SocketFactory", mWiFiBoundSocket, ret);
}
/**
* Returns a network given its interface name:
* "wifi" -> WIFI
* "cellular" -> Cellular
* etc...
*/
private void selectNetwork(@Nullable final String iface, @Nullable final String ipAddress) throws InterruptedException, IOException {
currentNetwork.setNetwork(null);
if (iface == null) return;
if (ipAddress != null) {
final Network cachedNetwork = mNetworkMap.get(iface + ipAddress);
if (cachedNetwork != null) {
currentNetwork.setNetwork(cachedNetwork);
return;
}
}
switch (iface) {
case "wifi":
requestNetwork(NetworkCapabilities.TRANSPORT_WIFI);
break;
case "cellular":
requestNetwork(NetworkCapabilities.TRANSPORT_CELLULAR);
break;
case "ethernet":
requestNetwork(NetworkCapabilities.TRANSPORT_ETHERNET);
break;
}
if (currentNetwork.getNetwork() == null) {
throw new IOException("Interface " + iface + " unreachable");
} else if (ipAddress != null && !ipAddress.equals("0.0.0.0"))
mNetworkMap.put(iface + ipAddress, currentNetwork.getNetwork());
}
@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);
}
@TargetApi(23)
private void registerNetworkCallbackV23() {
ConnectivityManager connectivityManager =
Assertions.checkNotNull(
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkRequest request =
new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.build();
networkCallback = new CapabilityValidatedCallback();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
/** Only callable on Lollipop and newer releases. */
@SuppressLint("NewApi")
public void registerNetworkCallback(NetworkCallback networkCallback) {
connectivityManager.registerNetworkCallback(
new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(),
networkCallback);
}
/** Only callable on Lollipop and newer releases. */
@SuppressLint("NewApi")
public void requestMobileNetwork(NetworkCallback networkCallback) {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connectivityManager.requestNetwork(builder.build(), networkCallback);
}
/**
* Should changes to connected network {@code network} be ignored?
* @param network Network to possibly consider ignoring changes to.
* @param capabilities {@code NetworkCapabilities} for {@code network} if known, otherwise
* {@code null}.
* @return {@code true} when either: {@code network} is an inaccessible VPN, or has already
* disconnected.
*/
private boolean ignoreConnectedInaccessibleVpn(
Network network, NetworkCapabilities capabilities) {
// Fetch capabilities if not provided.
if (capabilities == null) {
capabilities = mConnectivityManagerDelegate.getNetworkCapabilities(network);
}
// Ignore inaccessible VPNs as they don't apply to Chrome.
return capabilities == null
|| capabilities.hasTransport(TRANSPORT_VPN)
&& !mConnectivityManagerDelegate.vpnAccessible(network);
}
@TargetApi(Build.VERSION_CODES.P)
private void syncRequiredNetworkAndType(NetworkRequest networkRequest, Integer networkType) {
if (networkType == null) {
if (networkRequest == null) {
this.networkType = NETWORK_TYPE_NONE;
} else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
this.networkType = NETWORK_TYPE_UNMETERED;
} else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)) {
this.networkType = NETWORK_TYPE_NOT_ROAMING;
} else if (networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
this.networkType = NETWORK_TYPE_CELLULAR;
} else {
this.networkType = NETWORK_TYPE_ANY;
}
} else {
final NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
if (networkType == NETWORK_TYPE_UNMETERED) {
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
} else if (networkType == NETWORK_TYPE_NOT_ROAMING) {
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
} else if (networkType == NETWORK_TYPE_CELLULAR) {
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
}
this.networkRequest = builder.build();
}
}
@SuppressWarnings("unused")
private static boolean isCongestionDelayed(JobStatus jobStatus, Network network,
NetworkCapabilities capabilities, Constants constants) {
// If network is congested, and job is less than 50% through the
// developer-requested window, then we're okay delaying the job.
if (!capabilities.hasCapability(NET_CAPABILITY_NOT_CONGESTED)) {
return jobStatus.getFractionRunTime() < constants.CONN_CONGESTION_DELAY_FRAC;
} else {
return false;
}
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
if (!networkCapabilities.toString().equals(mLastNetworkCapabilities)) {
mLastNetworkCapabilities = networkCapabilities.toString();
VpnStatus.logDebug(String.format("Network capabilities of %s: %s", network, networkCapabilities));
}
}
public void testWithWiFiNetwork() {
setupMockNetworks(new MockNetworkConfig[] {
new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_CELLULAR, FactoryRet.RETURNS_ANOTHER_FACTORY),
new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_CORRECT_FACTORY),
});
Socket ret = WiFiSocketFactory.createSocket(mMockContext);
assertNotNull("createSocket() should always return a Socket instance", ret);
assertEquals("Returned Socket should be created through SocketFactory", mWiFiBoundSocket, ret);
}
@SuppressWarnings("deprecation")
private static boolean isRoaming(ConnectivityManager connectivityManager, NetworkInfo networkInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return networkInfo.isRoaming();
}
try {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
} catch (Exception e) {
return networkInfo.isRoaming();
}
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
if (DEBUG) {
Slog.v(TAG, "onCapabilitiesChanged: " + network);
}
updateTrackedJobs(-1, network);
}
private static HashMap<String, Integer> makeTransportToNameMap() {
SparseArray<String> numberToName = MessageUtils.findMessageNames(
new Class[] { NetworkCapabilities.class }, new String[]{ "TRANSPORT_" });
HashMap<String, Integer> nameToNumber = new HashMap<>();
for (int i = 0; i < numberToName.size(); i++) {
// MessageUtils will fail to initialize if there are duplicate constant values, so there
// are no duplicates here.
nameToNumber.put(numberToName.valueAt(i), numberToName.keyAt(i));
}
return nameToNumber;
}
@VisibleForTesting
protected Vpn(Looper looper, Context context, INetworkManagementService netService,
int userHandle, SystemServices systemServices) {
mContext = context;
mNetd = netService;
mUserHandle = userHandle;
mLooper = looper;
mSystemServices = systemServices;
mPackage = VpnConfig.LEGACY_VPN;
mOwnerUID = getAppUid(mPackage, mUserHandle);
try {
netService.registerObserver(mObserver);
} catch (RemoteException e) {
Log.wtf(TAG, "Problem registering observer", e);
}
mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
"" /* subtypeName */);
mNetworkCapabilities = new NetworkCapabilities();
mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
updateCapabilities(null /* defaultNetwork */);
loadAlwaysOnPackage();
}