Class 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> 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>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intIndicates an access point based on a cablestatic final intIndicates a corporate routing server access point type (e.g. BIS etc.)static final intIndicates a 2g network access point typestatic final intIndicates a 3g network access point typestatic final intIndicates an unknown access point typestatic final intIndicates a wlan (802.11b/c/g/n) access point type -
Method Summary
Modifier and TypeMethodDescriptionvoidaddDefaultHeader(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.voidAdds a generic listener to a network error that is invoked before the exception is propagated.voidAdds a listener to be notified when progress updatesvoidaddToQueue(ConnectionRequest request) Adds the given network connection to the queue of executionvoidaddToQueueAndWait(ConnectionRequest request) Identical to add to queue but waits until the request is processed in the queue, this is useful for completely synchronous operations.addToQueueAsync(ConnectionRequest request) Identical to add to queue but returns an AsyncResource object that will resolve to the ConnectionRequest.voidassignToThread(Class requestType, int offset) Makes sure the given class (subclass of ConnectionRequest) is always assigned to the given thread number.This method returns all pending ConnectioRequest connections.String[]getAPIds()Returns the ids of the access points available if supportedReturns the user displayable name for the given access pointintReturns the type of the access pointstatic StringThis URL is used to check whether an Internet connection is availableReturns the id of the current access pointstatic NetworkManagerReturns the singleton instance of this classintThe number of threadsintReturns the timeout durationbooleanIndicates whether looking up an access point is supported by this devicebooleanIndicates that the network queue is idlebooleanBest-effort check for whether a VPN appears to be active.booleanIndicates whether the current platform supports best-effort VPN detection.voidkillAndWait(ConnectionRequest request) Kills the given request and waits until the request is killed if it is being processed by one of the threads.voidRemoves the given error listenervoidAdds a listener to be notified when progress updatesstatic voidsetAutoDetectURL(String aAutoDetectURL) This URL is used to check whether an Internet connection is availablevoidReturns the id of the current access pointvoidsetThreadCount(int threadCount) Thread count should never be changed when the network is running since it will have no effect.voidsetTimeout(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 MIDPvoidshutdown()Shuts down the network thread, this will trigger failures if you have network requestsvoidShuts down the network thread and waits for shutdown to completevoidstart()There is no need to invoke this method since the network manager is started implicitly.voidupdateThreadCount(int threadCount) Sets the number of network threads and restarts the network threads
-
Field Details
-
ACCESS_POINT_TYPE_UNKNOWN
public static final int ACCESS_POINT_TYPE_UNKNOWNIndicates an unknown access point type- See Also:
-
ACCESS_POINT_TYPE_WLAN
public static final int ACCESS_POINT_TYPE_WLANIndicates a wlan (802.11b/c/g/n) access point type- See Also:
-
ACCESS_POINT_TYPE_CABLE
public static final int ACCESS_POINT_TYPE_CABLEIndicates an access point based on a cable- See Also:
-
ACCESS_POINT_TYPE_NETWORK3G
public static final int ACCESS_POINT_TYPE_NETWORK3GIndicates a 3g network access point type- See Also:
-
ACCESS_POINT_TYPE_NETWORK2G
public static final int ACCESS_POINT_TYPE_NETWORK2GIndicates a 2g network access point type- See Also:
-
ACCESS_POINT_TYPE_CORPORATE
public static final int ACCESS_POINT_TYPE_CORPORATEIndicates a corporate routing server access point type (e.g. BIS etc.)- See Also:
-
-
Method Details
-
getAutoDetectURL
This URL is used to check whether an Internet connection is available
Returns
the autoDetectURL
-
setAutoDetectURL
This URL is used to check whether an Internet connection is available
Parameters
aAutoDetectURL: the autoDetectURL to set
-
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
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
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.
Since
7.0
-
addToQueueAndWait
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
Adds the given network connection to the queue of execution
Parameters
request: network request for execution
-
killAndWait
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
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
Removes the given error listener
Parameters
e: callback to remove
-
addProgressListener
Adds a listener to be notified when progress updates
Parameters
al: action listener
-
removeProgressListener
Adds a listener to be notified when progress updates
Parameters
al: action listener
-
assignToThread
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
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
Returns the ids of the access points available if supported
Returns
ids of access points
-
getAPType
Returns the type of the access point
Parameters
id: access point id
Returns
one of the supported access point types from network manager
-
getAPName
-
getCurrentAccessPoint
Returns the id of the current access point
Returns
id of the current access point
-
setCurrentAccessPoint
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
trueif#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
trueif a VPN appears to be active on the current connection.
-