FileDocCategorySizeDatePackage
Network.javaAPI DocAndroid 5.1 API15332Thu Mar 12 22:22:10 GMT 2015android.net

Network

public class Network extends Object implements android.os.Parcelable
Identifies a {@code Network}. This is supplied to applications via {@link ConnectivityManager.NetworkCallback} in response to the active {@link ConnectivityManager#requestNetwork} or passive {@link ConnectivityManager#registerNetworkCallback} calls. It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis through a targeted {@link SocketFactory} or process-wide via {@link ConnectivityManager#setProcessDefaultNetwork}.

Fields Summary
public final int
netId
private volatile NetworkBoundSocketFactory
mNetworkBoundSocketFactory
private volatile com.android.okhttp.ConnectionPool
mConnectionPool
private volatile com.android.okhttp.HostResolver
mHostResolver
private Object
mLock
private static final boolean
httpKeepAlive
private static final int
httpMaxConnections
private static final long
httpKeepAliveDurationMs
public static final Creator
CREATOR
Constructors Summary
public Network(int netId)

hide

  // 5 minutes.

          
       
        this.netId = netId;
    
public Network(Network that)

hide

        this.netId = that.netId;
    
Methods Summary
public voidbindSocket(java.net.Socket socket)
Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket will be sent on this {@code Network}, irrespective of any process-wide network binding set by {@link ConnectivityManager#setProcessDefaultNetwork}. The socket must not be connected.

        // Apparently, the kernel doesn't update a connected TCP socket's routing upon mark changes.
        if (socket.isConnected()) {
            throw new SocketException("Socket is connected");
        }
        // Query a property of the underlying socket to ensure that the socket's file descriptor
        // exists, is available to bind to a network and is not closed.
        socket.getReuseAddress();
        bindSocketFd(socket.getFileDescriptor$());
    
public voidbindSocket(java.net.DatagramSocket socket)
Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the socket will be sent on this {@code Network}, irrespective of any process-wide network binding set by {@link ConnectivityManager#setProcessDefaultNetwork}. The socket must not be connected.

        // Apparently, the kernel doesn't update a connected UDP socket's routing upon mark changes.
        if (socket.isConnected()) {
            throw new SocketException("Socket is connected");
        }
        // Query a property of the underlying socket to ensure that the socket's file descriptor
        // exists, is available to bind to a network and is not closed.
        socket.getReuseAddress();
        bindSocketFd(socket.getFileDescriptor$());
    
private voidbindSocketFd(java.io.FileDescriptor fd)

        int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
        if (err != 0) {
            // bindSocketToNetwork returns negative errno.
            throw new ErrnoException("Binding socket to network " + netId, -err)
                    .rethrowAsSocketException();
        }
    
public intdescribeContents()

        return 0;
    
public booleanequals(java.lang.Object obj)


    
        
        if (obj instanceof Network == false) return false;
        Network other = (Network)obj;
        return this.netId == other.netId;
    
public java.net.InetAddress[]getAllByName(java.lang.String host)
Operates the same as {@code InetAddress.getAllByName} except that host resolution is done on this network.

param
host the hostname or literal IP string to be resolved.
return
the array of addresses associated with the specified host.
throws
UnknownHostException if the address lookup fails.

        return InetAddress.getAllByNameOnNet(host, netId);
    
public java.net.InetAddressgetByName(java.lang.String host)
Operates the same as {@code InetAddress.getByName} except that host resolution is done on this network.

param
host the hostName to be resolved to an address or {@code null}.
return
the {@code InetAddress} instance representing the host.
throws
UnknownHostException if the address lookup fails.

        return InetAddress.getByNameOnNet(host, netId);
    
public javax.net.SocketFactorygetSocketFactory()
Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by this factory will have its traffic sent over this {@code Network}. Note that if this {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the past or future will cease to work.

return
a {@link SocketFactory} which produces {@link Socket} instances bound to this {@code Network}.

        if (mNetworkBoundSocketFactory == null) {
            synchronized (mLock) {
                if (mNetworkBoundSocketFactory == null) {
                    mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId);
                }
            }
        }
        return mNetworkBoundSocketFactory;
    
public inthashCode()

        return netId * 11;
    
private voidmaybeInitHttpClient()

        synchronized (mLock) {
            if (mHostResolver == null) {
                mHostResolver = new HostResolver() {
                    @Override
                    public InetAddress[] getAllByName(String host) throws UnknownHostException {
                        return Network.this.getAllByName(host);
                    }
                };
            }
            if (mConnectionPool == null) {
                mConnectionPool = new ConnectionPool(httpMaxConnections,
                        httpKeepAliveDurationMs);
            }
        }
    
public java.net.URLConnectionopenConnection(java.net.URL url)
Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.

return
a {@code URLConnection} to the resource referred to by this URL.
throws
MalformedURLException if the URL protocol is not HTTP or HTTPS.
throws
IOException if an error occurs while opening the connection.
see
java.net.URL#openConnection()

        final ConnectivityManager cm = ConnectivityManager.getInstance();
        // TODO: Should this be optimized to avoid fetching the global proxy for every request?
        ProxyInfo proxyInfo = cm.getGlobalProxy();
        if (proxyInfo == null) {
            // TODO: Should this be optimized to avoid fetching LinkProperties for every request?
            final LinkProperties lp = cm.getLinkProperties(this);
            if (lp != null) proxyInfo = lp.getHttpProxy();
        }
        java.net.Proxy proxy = null;
        if (proxyInfo != null) {
            proxy = proxyInfo.makeProxy();
        } else {
            proxy = java.net.Proxy.NO_PROXY;
        }
        return openConnection(url, proxy);
    
public java.net.URLConnectionopenConnection(java.net.URL url, java.net.Proxy proxy)
Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.

param
proxy the proxy through which the connection will be established.
return
a {@code URLConnection} to the resource referred to by this URL.
throws
MalformedURLException if the URL protocol is not HTTP or HTTPS.
throws
IllegalArgumentException if the argument proxy is null.
throws
IOException if an error occurs while opening the connection.
see
java.net.URL#openConnection()
hide

        if (proxy == null) throw new IllegalArgumentException("proxy is null");
        maybeInitHttpClient();
        String protocol = url.getProtocol();
        OkHttpClient client;
        // TODO: HttpHandler creates OkHttpClients that share the default ResponseCache.
        // Could this cause unexpected behavior?
        if (protocol.equals("http")) {
            client = HttpHandler.createHttpOkHttpClient(proxy);
        } else if (protocol.equals("https")) {
            client = HttpsHandler.createHttpsOkHttpClient(proxy);
        } else {
            // OkHttpClient only supports HTTP and HTTPS and returns a null URLStreamHandler if
            // passed another protocol.
            throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
        }
        return client.setSocketFactory(getSocketFactory())
                .setHostResolver(mHostResolver)
                .setConnectionPool(mConnectionPool)
                .open(url);
    
public java.lang.StringtoString()

        return Integer.toString(netId);
    
public voidwriteToParcel(android.os.Parcel dest, int flags)

        dest.writeInt(netId);