public final class NetworkManager
- Object
- 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 = 1 | Indicates an unknown access point type |
public static final int ACCESS_POINT_TYPE_WLAN = 2 | Indicates a wlan (802.11b/c/g/n) access point type |
public static final int ACCESS_POINT_TYPE_CABLE = 3 | Indicates an access point based on a cable |
public static final int ACCESS_POINT_TYPE_NETWORK3G = 4 | Indicates a 3g network access point type |
public static final int ACCESS_POINT_TYPE_NETWORK2G = 5 | Indicates a 2g network access point type |
public static final int ACCESS_POINT_TYPE_CORPORATE = 6 | Indicates a corporate routing server access point type (e.g. BIS etc.) |
public static final int NETWORK_TYPE_NONE = 0 | Active network type reported by getCurrentNetworkType() / NetworkTypeListener: no usable connectivity. |
public static final int NETWORK_TYPE_WIFI = 1 | Active network type: WiFi / 802.11 / WLAN. |
public static final int NETWORK_TYPE_CELLULAR = 2 | Active network type: cellular data (2G/3G/4G/5G). |
public static final int NETWORK_TYPE_ETHERNET = 3 | Active network type: wired Ethernet. |
public static final int NETWORK_TYPE_BLUETOOTH = 4 | Active network type: short-range Bluetooth PAN. |
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. |
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 = 1ACCESS_POINT_TYPE_WLAN
public static final int ACCESS_POINT_TYPE_WLAN = 2ACCESS_POINT_TYPE_CABLE
public static final int ACCESS_POINT_TYPE_CABLE = 3ACCESS_POINT_TYPE_NETWORK3G
public static final int ACCESS_POINT_TYPE_NETWORK3G = 4ACCESS_POINT_TYPE_NETWORK2G
public static final int ACCESS_POINT_TYPE_NETWORK2G = 5ACCESS_POINT_TYPE_CORPORATE
public static final int ACCESS_POINT_TYPE_CORPORATE = 6NETWORK_TYPE_NONE
public static final int NETWORK_TYPE_NONE = 0getCurrentNetworkType() /
NetworkTypeListener: no usable connectivity.NETWORK_TYPE_WIFI
public static final int NETWORK_TYPE_WIFI = 1NETWORK_TYPE_CELLULAR
public static final int NETWORK_TYPE_CELLULAR = 2NETWORK_TYPE_ETHERNET
public static final int NETWORK_TYPE_ETHERNET = 3NETWORK_TYPE_BLUETOOTH
public static final int NETWORK_TYPE_BLUETOOTH = 4NETWORK_TYPE_OTHER
public static final int NETWORK_TYPE_OTHER = 5Method details
getAutoDetectURL
public static String getAutoDetectURL()Returns
setAutoDetectURL
public static void setAutoDetectURL(String aAutoDetectURL)Parameters
aAutoDetectURLString- the autoDetectURL to set
getInstance
public static NetworkManager getInstance()Returns
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()getThreadCount
public int getThreadCount()Returns
setThreadCount
public void setThreadCount(int threadCount)#updateThreadCount(int)Parameters
threadCountint- the threadCount to set
updateThreadCount
public void updateThreadCount(int threadCount)Parameters
threadCountint- the new number of threads
start
public void start()shutdown
public void shutdown()shutdownSync
public void shutdownSync()addDefaultHeader
public void addDefaultHeader(String key, String value)Parameters
keyString- the key of the header
valueString- the value of the header
addToQueueAsync
public AsyncResource<ConnectionRequest> addToQueueAsync(ConnectionRequest request)Parameters
requestConnectionRequest- the request object to add.
Returns
addToQueueAndWait
public void addToQueueAndWait(ConnectionRequest request)Parameters
requestConnectionRequest- the request object to add
addToQueue
public void addToQueue(ConnectionRequest request)Parameters
requestConnectionRequest- network request for execution
killAndWait
public void killAndWait(ConnectionRequest request)getTimeout
public int getTimeout()Returns
setTimeout
public void setTimeout(int t)Parameters
tint- the timeout duration
addErrorListener
public void addErrorListener(ActionListener<NetworkEvent> e)Parameters
eActionListener<NetworkEvent>- callback will be invoked with the Exception as the source object
removeErrorListener
public void removeErrorListener(ActionListener<NetworkEvent> e)Parameters
eActionListener<NetworkEvent>- callback to remove
addProgressListener
public void addProgressListener(ActionListener<NetworkEvent> al)Parameters
alActionListener<NetworkEvent>- action listener
removeProgressListener
public void removeProgressListener(ActionListener<NetworkEvent> al)Parameters
alActionListener<NetworkEvent>- action listener
assignToThread
public void assignToThread(Class requestType, int offset)Parameters
requestTypeClass- the class of the specific connection request
offsetint- the offset of the thread starting from 0 and smaller than thread count
enumurateQueue
public Enumeration enumurateQueue()Returns
isQueueIdle
public boolean isQueueIdle()Returns
isAPSupported
public boolean isAPSupported()Returns
getAPIds
public String[] getAPIds()Returns
getAPType
public int getAPType(String id)Parameters
idString- access point id
Returns
getAPName
public String getAPName(String id)Parameters
idString- the id of the access point
Returns
getCurrentAccessPoint
public String getCurrentAccessPoint()Returns
setCurrentAccessPoint
public void setCurrentAccessPoint(String id)Parameters
idString- id of the current access point
isVPNDetectionSupported
public boolean isVPNDetectionSupported()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()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
urlString- the URL to probe; typically a small static endpoint
timeoutMillisint- maximum time to wait for the request to complete; pass 0 to use the connection’s default timeout
Returns
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)addNetworkTypeListener(NetworkTypeListener). If the last listener is
removed the platform watcher is torn down too.fireNetworkTypeChange
public void fireNetworkTypeChange(int newType, boolean vpnActive)