public final class NetworkManager

  1. Object
  2. NetworkManager

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;
    }
}

Fields

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

Methods

public static String getAutoDetectURL()This URL is used to check whether an Internet connection is available
public static void setAutoDetectURL(String aAutoDetectURL)This URL is used to check whether an Internet connection is available
public static NetworkManager getInstance()Returns the singleton instance of this class
public static void setNetworkGuard(NetworkGuard guard)Installs the app-wide NetworkGuard.
public static synchronized NetworkGuard getNetworkGuard()The installed guard, or null when none was installed.
public int getThreadCount()The number of threads
public void setThreadCount(int threadCount)Deprecated Thread count should never be changed when the network is running since it will have no effect.
public void updateThreadCount(int threadCount)Sets the number of network threads and restarts the network threads
public void start()There is no need to invoke this method since the network manager is started implicitly.
public void shutdown()Deprecated Shuts down the network thread, this will trigger failures if you have network requests
public void shutdownSync()Shuts down the network thread and waits for shutdown to complete
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.
public AsyncResource<ConnectionRequest> addToQueueAsync(ConnectionRequest request)Identical to add to queue but returns an AsyncResource object that will resolve to the ConnectionRequest.
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.
public void addToQueue(ConnectionRequest request)Adds the given network connection to the queue of execution
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.
public int getTimeout()Returns the timeout duration
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
public void addErrorListener(ActionListener<NetworkEvent> e)Adds a generic listener to a network error that is invoked before the exception is propagated.
public void removeErrorListener(ActionListener<NetworkEvent> e)Removes the given error listener
public void addProgressListener(ActionListener<NetworkEvent> al)Adds a listener to be notified when progress updates
public void removeProgressListener(ActionListener<NetworkEvent> al)Adds a listener to be notified when progress updates
public void assignToThread(Class requestType, int offset)Makes sure the given class (subclass of ConnectionRequest) is always assigned to the given thread number.
public Enumeration enumurateQueue()This method returns all pending ConnectioRequest connections.
public boolean isQueueIdle()Indicates that the network queue is idle
public boolean isAPSupported()Indicates whether looking up an access point is supported by this device
public String[] getAPIds()Returns the ids of the access points available if supported
public int getAPType(String id)Returns the type of the access point
public String getAPName(String id)Returns the user displayable name for the given access point
public String getCurrentAccessPoint()Returns the id of the current access point
public void setCurrentAccessPoint(String id)Returns the id of the current access point
public boolean isVPNDetectionSupported()Indicates whether the current platform supports best-effort VPN detection.
public boolean isVPNActive()Best-effort check for whether a VPN appears to be active.
public int getCurrentNetworkType()Returns the device’s currently active network type, one of the NETWORK_TYPE_* constants.
public boolean isConnected()Fast best-effort connectivity check.
public boolean ping(String url, int timeoutMillis)Issues a blocking HTTP HEAD request to url and returns whether the server responded within timeoutMillis.
public void addNetworkTypeListener(NetworkTypeListener l)Registers l to be notified when the device’s active network type changes (WiFi <-> Cellular <-> None <-> …).
public void removeNetworkTypeListener(NetworkTypeListener l)Removes a listener previously registered with addNetworkTypeListener(NetworkTypeListener).
public void fireNetworkTypeChange(int newType, boolean vpnActive)Internal: invoked by platform implementations to deliver a network type change event.

Inherited methods

Field details

ACCESS_POINT_TYPE_UNKNOWN

public static final int ACCESS_POINT_TYPE_UNKNOWN = 1
Indicates an unknown access point type

ACCESS_POINT_TYPE_WLAN

public static final int ACCESS_POINT_TYPE_WLAN = 2
Indicates a wlan (802.11b/c/g/n) access point type

ACCESS_POINT_TYPE_CABLE

public static final int ACCESS_POINT_TYPE_CABLE = 3
Indicates an access point based on a cable

ACCESS_POINT_TYPE_NETWORK3G

public static final int ACCESS_POINT_TYPE_NETWORK3G = 4
Indicates a 3g network access point type

ACCESS_POINT_TYPE_NETWORK2G

public static final int ACCESS_POINT_TYPE_NETWORK2G = 5
Indicates a 2g network access point type

ACCESS_POINT_TYPE_CORPORATE

public static final int ACCESS_POINT_TYPE_CORPORATE = 6
Indicates a corporate routing server access point type (e.g. BIS etc.)

NETWORK_TYPE_NONE

public static final int NETWORK_TYPE_NONE = 0
Active network type reported by getCurrentNetworkType() / NetworkTypeListener: no usable connectivity.

NETWORK_TYPE_WIFI

public static final int NETWORK_TYPE_WIFI = 1
Active network type: WiFi / 802.11 / WLAN.

NETWORK_TYPE_CELLULAR

public static final int NETWORK_TYPE_CELLULAR = 2
Active network type: cellular data (2G/3G/4G/5G).

NETWORK_TYPE_ETHERNET

public static final int NETWORK_TYPE_ETHERNET = 3
Active network type: wired Ethernet.

NETWORK_TYPE_BLUETOOTH

public static final int NETWORK_TYPE_BLUETOOTH = 4
Active network type: short-range Bluetooth PAN.

NETWORK_TYPE_OTHER

public static final int NETWORK_TYPE_OTHER = 5
Active network type reported by the platform but not classified into one of the named buckets above.

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 String
the autoDetectURL to set

getInstance

public static NetworkManager getInstance()
Returns the singleton instance of this class

Returns

instance of this class

setNetworkGuard

public static void setNetworkGuard(NetworkGuard guard)

Installs the app-wide NetworkGuard.

The first call wins and the slot then seals. A guard can veto requests and enforce certificate pins, so allowing it to be replaced at runtime would let any code that runs later – including code an attacker injected – swap in a permissive one.

Throws

IllegalStateException
if a guard is already installed

getNetworkGuard

public static synchronized NetworkGuard getNetworkGuard()
The installed guard, or null when none was installed.

getThreadCount

public int getThreadCount()
The number of threads

Returns

the threadCount

setThreadCount

public void setThreadCount(int threadCount)
Deprecated. since the network is always running in Codename One this method is quite confusing unfortunately fixing it will probably break working code. You should migrate the code to use #updateThreadCount(int)
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 int
the threadCount to set

updateThreadCount

public void updateThreadCount(int threadCount)
Sets the number of network threads and restarts the network threads

Parameters

threadCount int
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()
Deprecated. This method is for internal use only
Shuts down the network thread, this will trigger failures if you have network requests

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 String
the key of the header
value String
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 ConnectionRequest
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 ConnectionRequest
the request object to add

addToQueue

public void addToQueue(ConnectionRequest request)
Adds the given network connection to the queue of execution

Parameters

request ConnectionRequest
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!

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 int
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 ActionListener<NetworkEvent>
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 ActionListener<NetworkEvent>
callback to remove

addProgressListener

public void addProgressListener(ActionListener<NetworkEvent> al)
Adds a listener to be notified when progress updates

Parameters

al ActionListener<NetworkEvent>
action listener

removeProgressListener

public void removeProgressListener(ActionListener<NetworkEvent> al)
Adds a listener to be notified when progress updates

Parameters

al ActionListener<NetworkEvent>
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 Class
the class of the specific connection request
offset int
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 String
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 String
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 String
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 String
the URL to probe; typically a small static endpoint
timeoutMillis int
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.