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> 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 Details

    • ACCESS_POINT_TYPE_UNKNOWN

      public static final int ACCESS_POINT_TYPE_UNKNOWN
      Indicates an unknown access point type
      See Also:
    • 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:
    • ACCESS_POINT_TYPE_CABLE

      public static final int ACCESS_POINT_TYPE_CABLE
      Indicates an access point based on a cable
      See Also:
    • ACCESS_POINT_TYPE_NETWORK3G

      public static final int ACCESS_POINT_TYPE_NETWORK3G
      Indicates a 3g network access point type
      See Also:
    • ACCESS_POINT_TYPE_NETWORK2G

      public static final int ACCESS_POINT_TYPE_NETWORK2G
      Indicates a 2g network access point type
      See Also:
    • 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:
  • 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.

      Since

      7.0

    • 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.