# Class NetworkManager

java.lang.Object
com.codename1.io.NetworkManager

public final class NetworkManager extends Object

Main entry point for managing the connection requests, this is essentially a threaded queue that makes sure to route all connections via the network thread while sending the callbacks through the Codename One EDT.

The sample code below fetches a page of data from the nestoria housing listing API.

You can see instructions on how to display the data in the `com.codename1.components.InfiniteScrollAdapter` class. You can read more about networking in Codename One `here`

    int pageNumber = 1;
    java.util.List<Map<String, Object>> fetchPropertyData(String text) {
        try {
            ConnectionRequest r = new ConnectionRequest();
            r.setPost(false);
            r.setUrl("http://api.nestoria.co.uk/api");
            r.addArgument("pretty", "0");
            r.addArgument("action", "search_listings");
            r.addArgument("encoding", "json");
            r.addArgument("listing_type", "buy");
            r.addArgument("page", "" + pageNumber);
            pageNumber++;
            r.addArgument("country", "uk");
            r.addArgument("place_name", text);
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            Map response = (Map)result.get("response");
            return (java.util.List<Map<String, Object>>)response.get("listings");
        } catch(Exception err) {
            Log.e(err);
            return null;
        }
    }

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `static final int`
  `ACCESS_POINT_TYPE_CABLE`
  Indicates an access point based on a cable
  `static final int`
  `ACCESS_POINT_TYPE_CORPORATE`
  Indicates a corporate routing server access point type (e.g. BIS etc.)
  `static final int`
  `ACCESS_POINT_TYPE_NETWORK2G`
  Indicates a 2g network access point type
  `static final int`
  `ACCESS_POINT_TYPE_NETWORK3G`
  Indicates a 3g network access point type
  `static final int`
  `ACCESS_POINT_TYPE_UNKNOWN`
  Indicates an unknown access point type
  `static final int`
  `ACCESS_POINT_TYPE_WLAN`
  Indicates a wlan (802.11b/c/g/n) access point type
  `static final int`
  `NETWORK_TYPE_BLUETOOTH`
  Active network type: short-range Bluetooth PAN.
  `static final int`
  `NETWORK_TYPE_CELLULAR`
  Active network type: cellular data (2G/3G/4G/5G).
  `static final int`
  `NETWORK_TYPE_ETHERNET`
  Active network type: wired Ethernet.
  `static final int`
  `NETWORK_TYPE_NONE`
  Active network type reported by `getCurrentNetworkType()` / `NetworkTypeListener`: no usable connectivity.
  `static final int`
  `NETWORK_TYPE_OTHER`
  Active network type reported by the platform but not classified into one of the named buckets above.
  `static final int`
  `NETWORK_TYPE_WIFI`
  Active network type: WiFi / 802.11 / WLAN.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addDefaultHeader(String key, String value)`
  Adds a header to the global default headers, this header will be implicitly added to all requests going out from this point onwards.
  `void`
  `addErrorListener(ActionListener<NetworkEvent> e)`
  Adds a generic listener to a network error that is invoked before the exception is propagated.
  `void`
  `addNetworkTypeListener(NetworkTypeListener l)`
  Registers `l` to be notified when the device's active network type changes (WiFi <-> Cellular <-> None <-> ...).
  `void`
  `addProgressListener(ActionListener<NetworkEvent> al)`
  Adds a listener to be notified when progress updates
  `void`
  `addToQueue(ConnectionRequest request)`
  Adds the given network connection to the queue of execution
  `void`
  `addToQueueAndWait(ConnectionRequest request)`
  Identical to add to queue but waits until the request is processed in the queue, this is useful for completely synchronous operations.
  `AsyncResource<ConnectionRequest>`
  `addToQueueAsync(ConnectionRequest request)`
  Identical to add to queue but returns an AsyncResource object that will resolve to the ConnectionRequest.
  `void`
  `assignToThread(Class requestType, int offset)`
  Makes sure the given class (subclass of ConnectionRequest) is always assigned to the given thread number.
  `Enumeration`
  `enumurateQueue()`
  This method returns all pending ConnectioRequest connections.
  `void`
  `fireNetworkTypeChange(int newType, boolean vpnActive)`
  Internal: invoked by platform implementations to deliver a network type change event.
  `String[]`
  `getAPIds()`
  Returns the ids of the access points available if supported
  `String`
  `getAPName(String id)`
  Returns the user displayable name for the given access point
  `int`
  `getAPType(String id)`
  Returns the type of the access point
  `static String`
  `getAutoDetectURL()`
  This URL is used to check whether an Internet connection is available
  `String`
  `getCurrentAccessPoint()`
  Returns the id of the current access point
  `int`
  `getCurrentNetworkType()`
  Returns the device's currently active network type, one of the `NETWORK_TYPE_*` constants.
  `static NetworkManager`
  `getInstance()`
  Returns the singleton instance of this class
  `int`
  `getThreadCount()`
  The number of threads
  `int`
  `getTimeout()`
  Returns the timeout duration
  `boolean`
  `isAPSupported()`
  Indicates whether looking up an access point is supported by this device
  `boolean`
  `isConnected()`
  Fast best-effort connectivity check.
  `boolean`
  `isQueueIdle()`
  Indicates that the network queue is idle
  `boolean`
  `isVPNActive()`
  Best-effort check for whether a VPN appears to be active.
  `boolean`
  `isVPNDetectionSupported()`
  Indicates whether the current platform supports best-effort VPN detection.
  `void`
  `killAndWait(ConnectionRequest request)`
  Kills the given request and waits until the request is killed if it is being processed by one of the threads.
  `boolean`
  `ping(String url, int timeoutMillis)`
  Issues a blocking HTTP HEAD request to `url` and returns whether the server responded within `timeoutMillis`.
  `void`
  `removeErrorListener(ActionListener<NetworkEvent> e)`
  Removes the given error listener
  `void`
  `removeNetworkTypeListener(NetworkTypeListener l)`
  Removes a listener previously registered with `addNetworkTypeListener(NetworkTypeListener)`.
  `void`
  `removeProgressListener(ActionListener<NetworkEvent> al)`
  Adds a listener to be notified when progress updates
  `static void`
  `setAutoDetectURL(String aAutoDetectURL)`
  This URL is used to check whether an Internet connection is available
  `void`
  `setCurrentAccessPoint(String id)`
  Returns the id of the current access point
  `void`
  `setThreadCount(int threadCount)`
  Thread count should never be changed when the network is running since it will have no effect.
  `void`
  `setTimeout(int t)`
  Sets the timeout in milliseconds for network connections, a timeout may be "faked" for platforms that don't support the notion of a timeout such as MIDP
  `void`
  `shutdown()`
  Shuts down the network thread, this will trigger failures if you have network requests
  `void`
  `shutdownSync()`
  Shuts down the network thread and waits for shutdown to complete
  `void`
  `start()`
  There is no need to invoke this method since the network manager is started implicitly.
  `void`
  `updateThreadCount(int threadCount)`
  Sets the number of network threads and restarts the network threads

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Field Details

  - ### ACCESS_POINT_TYPE_UNKNOWN

    public static final int ACCESS_POINT_TYPE_UNKNOWN
    Indicates an unknown access point type
    See Also:
      - Constant Field Values

  - ### ACCESS_POINT_TYPE_WLAN

    public static final int ACCESS_POINT_TYPE_WLAN
    Indicates a wlan (802.11b/c/g/n) access point type
    See Also:
      - Constant Field Values

  - ### ACCESS_POINT_TYPE_CABLE

    public static final int ACCESS_POINT_TYPE_CABLE
    Indicates an access point based on a cable
    See Also:
      - Constant Field Values

  - ### ACCESS_POINT_TYPE_NETWORK3G

    public static final int ACCESS_POINT_TYPE_NETWORK3G
    Indicates a 3g network access point type
    See Also:
      - Constant Field Values

  - ### ACCESS_POINT_TYPE_NETWORK2G

    public static final int ACCESS_POINT_TYPE_NETWORK2G
    Indicates a 2g network access point type
    See Also:
      - Constant Field Values

  - ### ACCESS_POINT_TYPE_CORPORATE

    public static final int ACCESS_POINT_TYPE_CORPORATE
    Indicates a corporate routing server access point type (e.g. BIS etc.)
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_NONE

    public static final int NETWORK_TYPE_NONE
    Active network type reported by `getCurrentNetworkType()` / `NetworkTypeListener`: no usable connectivity.
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_WIFI

    public static final int NETWORK_TYPE_WIFI
    Active network type: WiFi / 802.11 / WLAN.
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_CELLULAR

    public static final int NETWORK_TYPE_CELLULAR
    Active network type: cellular data (2G/3G/4G/5G).
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_ETHERNET

    public static final int NETWORK_TYPE_ETHERNET
    Active network type: wired Ethernet.
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_BLUETOOTH

    public static final int NETWORK_TYPE_BLUETOOTH
    Active network type: short-range Bluetooth PAN.
    See Also:
      - Constant Field Values

  - ### NETWORK_TYPE_OTHER

    public static final int NETWORK_TYPE_OTHER
    Active network type reported by the platform but not classified into one of the named buckets above.
    See Also:
      - Constant Field Values

- ## Method Details

  - ### getAutoDetectURL

    public static String getAutoDetectURL()

    This URL is used to check whether an Internet connection is available

    ###### Returns

    the autoDetectURL

  - ### setAutoDetectURL

    public static void setAutoDetectURL(String aAutoDetectURL)

    This URL is used to check whether an Internet connection is available

    ###### Parameters

    - `aAutoDetectURL`: the autoDetectURL to set

  - ### getInstance

    public static NetworkManager getInstance()

    Returns the singleton instance of this class

    ###### Returns

    instance of this class

  - ### getThreadCount

    public int getThreadCount()

    The number of threads

    ###### Returns

    the threadCount

  - ### setThreadCount

    public void setThreadCount(int threadCount)

    Thread count should never be changed when the network is running since it will have no effect. Increasing the thread count can bring many race conditions and problems to the surface, furthermore MIDP doesn't require support for more than one network thread hence increasing the thread count might fail.

    ###### Parameters

    - `threadCount`: the threadCount to set

    ###### Deprecated

  - ### updateThreadCount

    public void updateThreadCount(int threadCount)

    Sets the number of network threads and restarts the network threads

    ###### Parameters

    - `threadCount`: the new number of threads

  - ### start

    public void start()
    There is no need to invoke this method since the network manager is started implicitly. It is useful only if you explicitly stop the network manager. Invoking this method otherwise will just do nothing.

  - ### shutdown

    public void shutdown()

    Shuts down the network thread, this will trigger failures if you have network requests

    ###### Deprecated

    This method is for internal use only

  - ### shutdownSync

    public void shutdownSync()
    Shuts down the network thread and waits for shutdown to complete

  - ### addDefaultHeader

    public void addDefaultHeader(String key, String value)

    Adds a header to the global default headers, this header will be implicitly added to all requests going out from this point onwards. The main use case for this is for authentication information communication via the header.

    ###### Parameters

    - `key`: the key of the header

    - `value`: the value of the header

  - ### addToQueueAsync

    public AsyncResource<ConnectionRequest> addToQueueAsync(ConnectionRequest request)

    Identical to add to queue but returns an AsyncResource object that will resolve to the ConnectionRequest.

    ###### Parameters

    - `request`: the request object to add.

    ###### Returns

    AsyncResource resolving to the connection request on complete.

  - ### addToQueueAndWait

    public void addToQueueAndWait(ConnectionRequest request)

    Identical to add to queue but waits until the request is processed in the queue, this is useful for completely synchronous operations.

    ###### Parameters

    - `request`: the request object to add

  - ### addToQueue

    public void addToQueue(ConnectionRequest request)

    Adds the given network connection to the queue of execution

    ###### Parameters

    - `request`: network request for execution

  - ### killAndWait

    public void killAndWait(ConnectionRequest request)

    Kills the given request and waits until the request is killed if it is being processed by one of the threads. This method must not be invoked from a network thread!

    ###### Parameters

    - `request`

  - ### getTimeout

    public int getTimeout()

    Returns the timeout duration

    ###### Returns

    timeout in milliseconds

  - ### setTimeout

    public void setTimeout(int t)

    Sets the timeout in milliseconds for network connections, a timeout may be "faked" for platforms that don't support the notion of a timeout such as MIDP

    ###### Parameters

    - `t`: the timeout duration

  - ### addErrorListener

    public void addErrorListener(ActionListener<NetworkEvent> e)

    Adds a generic listener to a network error that is invoked before the exception is propagated. Note that this handles also server error codes by default! You can change this default behavior setting to false ConnectionRequest.setHandleErrorCodesInGlobalErrorHandler(boolean). Consume the event in order to prevent it from propagating further.

    ###### Parameters

    - `e`: callback will be invoked with the Exception as the source object

  - ### removeErrorListener

    public void removeErrorListener(ActionListener<NetworkEvent> e)

    Removes the given error listener

    ###### Parameters

    - `e`: callback to remove

  - ### addProgressListener

    public void addProgressListener(ActionListener<NetworkEvent> al)

    Adds a listener to be notified when progress updates

    ###### Parameters

    - `al`: action listener

  - ### removeProgressListener

    public void removeProgressListener(ActionListener<NetworkEvent> al)

    Adds a listener to be notified when progress updates

    ###### Parameters

    - `al`: action listener

  - ### assignToThread

    public void assignToThread(Class requestType, int offset)

    Makes sure the given class (subclass of ConnectionRequest) is always assigned to the given thread number. This is useful for a case of an application that wants all background downloads to occur on one thread so it doesn't tie up the main network thread (but doesn't stop like a low priority request would).

    ###### Parameters

    - `requestType`: the class of the specific connection request

    - `offset`: the offset of the thread starting from 0 and smaller than thread count

  - ### enumurateQueue

    public Enumeration enumurateQueue()

    This method returns all pending ConnectioRequest connections.

    ###### Returns

    the queue elements

  - ### isQueueIdle

    public boolean isQueueIdle()

    Indicates that the network queue is idle

    ###### Returns

    true if no network activity is in progress or pending

  - ### isAPSupported

    public boolean isAPSupported()

    Indicates whether looking up an access point is supported by this device

    ###### Returns

    true if access point lookup is supported

  - ### getAPIds

    public String[] getAPIds()

    Returns the ids of the access points available if supported

    ###### Returns

    ids of access points

  - ### getAPType

    public int getAPType(String id)

    Returns the type of the access point

    ###### Parameters

    - `id`: access point id

    ###### Returns

    one of the supported access point types from network manager

  - ### getAPName

    public String getAPName(String id)

    Returns the user displayable name for the given access point

    ###### Parameters

    - `id`: the id of the access point

    ###### Returns

    the name of the access point

  - ### getCurrentAccessPoint

    public String getCurrentAccessPoint()

    Returns the id of the current access point

    ###### Returns

    id of the current access point

  - ### setCurrentAccessPoint

    public void setCurrentAccessPoint(String id)

    Returns the id of the current access point

    ###### Parameters

    - `id`: id of the current access point

  - ### isVPNDetectionSupported

    public boolean isVPNDetectionSupported()

    Indicates whether the current platform supports best-effort VPN detection.

    ###### Returns

    `true` if `#isVPNActive()` is implemented on this platform.

  - ### isVPNActive

    public boolean isVPNActive()

    Best-effort check for whether a VPN appears to be active.

    This value should be treated as advisory only. Platform APIs and interface-name heuristics can miss some VPN configurations and may also report non-VPN tunnels as VPNs.

    ###### Returns

    `true` if a VPN appears to be active on the current connection.

  - ### getCurrentNetworkType

    public int getCurrentNetworkType()
    Returns the device's currently active network type, one of the `NETWORK_TYPE_*` constants. Returns `NETWORK_TYPE_NONE` when there is no connectivity. Distinct from `getAPType` which describes a configured access point rather than the active data path.

  - ### isConnected

    public boolean isConnected()

    Fast best-effort connectivity check. Returns `false` only when the platform reports `NETWORK_TYPE_NONE`; all other states (WiFi, cellular, ethernet, VPN-only, or "other") return `true`. Avoids the HTTP probe that `getInstance().assignToThread(...)` performs against `autoDetectURL` so the check is suitable to call from the EDT.

    Apps that need a stronger "can I reach my server" guarantee should still fire a real `ConnectionRequest`; this method only reports whether the device has any usable network interface up.

  - ### ping

    public boolean ping(String url, int timeoutMillis)

    Issues a blocking HTTP HEAD request to `url` and returns whether the server responded within `timeoutMillis`. Any response - including 4xx or 5xx - is treated as a successful ping (the network round-trip completed). Only socket errors, DNS failures, and timeouts return false.

    Use this for reachability probes against a known endpoint when `isConnected()` (a fast device-side network-type check) isn't strong enough. Must not be invoked from the EDT.

    ###### Parameters

    - `url`: the URL to probe; typically a small static endpoint

    - `timeoutMillis`: maximum time to wait for the request to complete; pass 0 to use the connection's default timeout

    ###### Returns

    true if the server responded, false on timeout, DNS, or socket error

  - ### addNetworkTypeListener

    public void addNetworkTypeListener(NetworkTypeListener l)

    Registers `l` to be notified when the device's active network type changes (WiFi <-> Cellular <-> None <-> ...). The listener is invoked on the EDT. Safe to call multiple times with the same listener; only the first registration takes effect.

    On platforms where network change events are unavailable the listener is still installed but never fires; `getCurrentNetworkType()` should be polled instead.

  - ### removeNetworkTypeListener

    public void removeNetworkTypeListener(NetworkTypeListener l)
    Removes a listener previously registered with `addNetworkTypeListener(NetworkTypeListener)`. If the last listener is removed the platform watcher is torn down too.

  - ### fireNetworkTypeChange

    public void fireNetworkTypeChange(int newType, boolean vpnActive)
    Internal: invoked by platform implementations to deliver a network type change event. Public so platform code in other packages can call it; not intended for application use.