Warning Older Docs! - You are viewing documentation for a previous released version of RhoMobile Suite.

Network

This API class allows you to interact with either the WAN or WiFI network of the device.

Enabling the API

This API is part of the coreapi extension that is included automatically.

extensions: ["coreapi"]

JavaScript Usage

Be sure to review the JavaScript API Usage guide for important information about using this API in JavaScript.

Ruby Usage

Be sure to review the Ruby API Usage guide for important information about using this API in Ruby.

Methods

cancel(CallBackHandler callback)

Cancel the request identified by callback. If callback is not specified then all requests will be canceled.

Parameters

  • callback : CallBackHandler Optional

Synchronous Return:

  • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.cancel(CallBackHandler callback)
    • Ruby: Rho::Network.cancel(CallBackHandler callback)

connectWan(STRING connectionDestination, CallBackHandler callback)

Connects the device to a Wide Area Network. The connection destination must be first configured through the Connection Manager (on the device) and the destination name provided to this method. If a connection is already established, you must first call disconnectWan before attempting another connection. A list of available connection destinations is written to the log file when either connectWan or disconnectWan are first specified. Specify the connection as ‘Internet’ to use the default internet connection defined on the device. If the specified destination does not exist no connection attempt will be made and an entry will be made in the log file.

Parameters

  • connectionDestination : STRING

    The connection in the Windows Connection manager to use, specify ‘Internet’ to use the default internet connection.

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • phoneSignalStrength : STRING

      The signal strength of the phone as a percentage of maximum strength. Returned as a number between 0 and 100. If there is no phone service this field will be 0.

    • networkOperator : STRING

      The name of the current network operator associated with the SIM card.

    • connectionTypeAvailable : STRING

      The current data connection type available to RhoElements as provided by the Network. Values can be ‘Unavailable’, GPRS, 1XRTT, EVDO, EDGE, UMTS, EVDV or HSDPA.

    • connectionTypeConnected : STRING

      The data connection type to which the device is currently connected. The values returned are identical to connectionTypeAvailable, with the exception that ‘Not Connected’ replaces ‘Unavailable’.

    • connectionManagerMessage : STRING

      This is the last received status from the Connection Manager. Do NOT use this parameter to determine if you are able to physically send / receive data to a remote host, it only provides an indication of whether the Connection Manager believes the connection is available. To determine if you are connected to a remote host use the detectConnection method.

Synchronous Return:

  • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.connectWan(STRING connectionDestination, CallBackHandler callback)
    • Ruby: Rho::Network.connectWan(STRING connectionDestination, CallBackHandler callback)

detectConnection(HASH propertyMap, CallBackHandler callback)

Begins polling the specified host on the specified URL to check if there is a network connection available. The connection status is reported back via the provided callback. Note that callback will be called only if connection status has changed compared to previous polling.

Parameters

  • propertyMap : HASH

    Properties map.

    • host : STRING Default: www.motorolasolutions.com

      When detecting a network connection, this is the URL or IP address of the server to attempt to connect to.

    • port : INTEGER Default: 80

      When detecting a network connection, this is the port on the host to connect to.

    • pollInterval : INTEGER Default: 30000

      The time, in milliseconds, between each check for a connection. Note that the actual connection report interval will be the sum of the poll interval and the detection timeout. The minimum allowed value is 5000ms.

    • detectionTimeout : INTEGER Default: 1000

      The amount of time to attempt to connect to the specified URL before giving up and assuming ‘disconnected’. Value is specified in milliseconds.

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • connectionInformation : STRING

      Whether the device is connected to the specified host and port. Either ‘Connected’ or ‘Disconnected’.

    • failureMessage : STRING

      If the device is disconnected this field will contain information about why the connection failed.

Synchronous Return:

  • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.detectConnection(HASH propertyMap, CallBackHandler callback)
    • Ruby: Rho::Network.detectConnection(HASH propertyMap, CallBackHandler callback)

disconnectWan()

Disconnects the current WAN connection. DisconnectWan will only affect connections established by RhoElements so if you have not previously called connectWan this function will have no effect.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.disconnectWan()
    • Ruby: Rho::Network.disconnectWan()

downloadFile(HASH propertyMap, CallBackHandler callback)

Download a file to the specified filename. Note: if ‘overwriteFile’ flag is default or false, the HEAD request to the server will be performed before actual download to retrieve ‘last-modified’ header which is used to support resuming interrupted download. If targeted server doesn’t support HEAD requests, ‘overwriteFile’ should be set to true.

Parameters

  • propertyMap : HASH

    Properties to be used in this request.

    • url : STRING

      URL of file to be downloaded. HTTP and HTTPS protocols are supported.

    • filename : STRING

      The path and name of the file to be uploaded.

    • overwriteFile : BOOLEAN Default: false

      OverWriteFile will overwrite the destination file if it already exists.

    • createFolders : BOOLEAN Default: false

      CreateFolders can automatically create the directory path.

  • callback : CallBackHandler Optional

Async Callback Returning Parameters: HASH

    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

    • fileExists : BOOLEAN

      When overwriteFile is false and file exists, when error return and this flag set to true.

Synchronous Return:

  • HASH : this method also supports async callbacks - check the Callback tab for callback return parameters.
    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

    • fileExists : BOOLEAN

      When overwriteFile is false and file exists, when error return and this flag set to true.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.downloadFile(HASH propertyMap, CallBackHandler callback)
    • Ruby: Rho::Network.downloadFile(HASH propertyMap, CallBackHandler callback)

get(HASH propertyMap, CallBackHandler callback)

Perform a HTTP GET request.

Note: This method will perform a POST if you send a body with it. If performing a GET, do not add a body to the call.

Parameters

  • propertyMap : HASH

    Properties map.

    Valid `properties` for this parameter are the properties avaliable to this API module. Check the property section
  • callback : CallBackHandler Optional

Async Callback Returning Parameters: HASH

    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Synchronous Return:

  • HASH : this method also supports async callbacks - check the Callback tab for callback return parameters.
    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.get(HASH propertyMap, CallBackHandler callback)
    • Ruby: Rho::Network.get(HASH propertyMap, CallBackHandler callback)

hasCellNetwork()

Returns true if the device is connected to a cell network. Not supported on Windows CE.

Synchronous Return:

  • BOOLEAN

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.hasCellNetwork()
    • Ruby: Rho::Network.hasCellNetwork()

hasNetwork()

Returns true if the device is connected to a network. Not supported on Windows CE.

Synchronous Return:

  • BOOLEAN

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.hasNetwork()
    • Ruby: Rho::Network.hasNetwork()

hasWifiNetwork()

Returns true if the device is connected to a WiFi network. Not supported on Windows CE.

Synchronous Return:

  • BOOLEAN

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.hasWifiNetwork()
    • Ruby: Rho::Network.hasWifiNetwork()

post(HASH propertyMap, CallBackHandler callback)

Perform a HTTP Post.

Parameters

  • propertyMap : HASH

    The properties for the Network module can be used in this hash along with the following:

    • body : STRING

      The message body of the HTTP request.

  • callback : CallBackHandler Optional

Async Callback Returning Parameters: HASH

    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Synchronous Return:

  • HASH : this method also supports async callbacks - check the Callback tab for callback return parameters.
    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.post(HASH propertyMap, CallBackHandler callback)
    • Ruby: Rho::Network.post(HASH propertyMap, CallBackHandler callback)

startStatusNotify(INTEGER pollInterval, CallBackHandler callback)

Start network status notifications. Notifications are sent when WiFi or Cell network appear / disappear. To check real Internet connectivity use detectConnection method. Not supported on Windows CE.

Parameters

  • pollInterval : INTEGER Default: 20

    The network status polling period for systems that can not notify network status change immediately. In seconds. Currently applies to iOS only as immediate status notification is not available on this platform.

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: HASH

    • current_status : STRING

      Current status of network connection. Can be “connected” or “disconnected”.

    • prev_status : STRING

      Previous status of network connection. Can be “connected”, “disconnected” or “unknown”."

Synchronous Return:

  • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.startStatusNotify(INTEGER pollInterval, CallBackHandler callback)
    • Ruby: Rho::Network.startStatusNotify(INTEGER pollInterval, CallBackHandler callback)

stopDetectingConnection(CallBackHandler callback)

Ceases network detection. The callback parameter is no longer supported; it has been made optional to preserve backward compatibility.

Parameters

  • callback : CallBackHandler Optional

Synchronous Return:

  • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.stopDetectingConnection(CallBackHandler callback)
    • Ruby: Rho::Network.stopDetectingConnection(CallBackHandler callback)

stopStatusNotify()

Stop network status notifications. Not supported on Windows CE.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.stopStatusNotify()
    • Ruby: Rho::Network.stopStatusNotify()

uploadFile(HASH propertyMap, CallBackHandler callback)

Upload the specified file using HTTP POST.

Parameters

  • propertyMap : HASH

    The properties for the Network module can be used in this hash along with the following:

    • filename : STRING

      The path and name of the file to be uploaded.

    • body : STRING

      The message body of the HTTP request.

    • fileContentType : STRING

      Content-Type header for the file, defaults to “application/octet-stream”.

    • multipart : ARRAY

      Array of hashes containing file information.

      • Object : HASH

        Multipart properties.

        • filename : STRING

          The path and name of the file to be uploaded.

        • contentType : STRING

          Content-Type header, defaults to “application/octet-stream”.

        • filenameBase : STRING

          Base directory containing the :filename.

        • name : STRING

          File type, defaults to “blob”.

  • callback : CallBackHandler Optional

Async Callback Returning Parameters: HASH

    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Synchronous Return:

  • HASH : this method also supports async callbacks - check the Callback tab for callback return parameters.
    • body : STRING

      The body of the HTTP response.

    • headers : HASH

      A hash containing the response headers.

    • cookies : STRING

      The server cookies, parsed and usable for subsequent requests.

    • http_error : INTEGER

      HTTP error code if response code was not 200.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.Network.uploadFile(HASH propertyMap, CallBackHandler callback)
    • Ruby: Rho::Network.uploadFile(HASH propertyMap, CallBackHandler callback)

Properties

The properties of this API Class cannot be accessed via setter or getter methods (unless otherwise noted). However they can be used in methods that allow a HASH or Array of properties to be passed in.

authPassword : STRING

Password for basic authentication. You must also specify `authType=‘basic’

Property Access:

  • Class: This property can only be accessed via the API class object.
    • JavaScript: Rho.Network.authPassword
    • Ruby: Rho::Network.authPassword

This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

authType : STRING

Type of authentication used for this request. Check the list of available options below. Leaving blank will result in no authentication type.

Possible Values (STRING):

Constant: Rho.Network.AUTH_BASIC (For Ruby use "::" instead of ".")
String: basic

Basic Authentication Type. uses authUser and authPassword.

Property Access:

  • Class: This property can only be accessed via the API class object.
    • JavaScript: Rho.Network.authType
    • Ruby: Rho::Network.authType

This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

authUser : STRING

User name for basic authentication. You must also specify authType='basic'

Property Access:

  • Class: This property can only be accessed via the API class object.
    • JavaScript: Rho.Network.authUser
    • Ruby: Rho::Network.authUser

This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

headers : HASH

List of HTTP headers to be used in the network request.

Property Access:

  • Class: This property can only be accessed via the API class object.
    • JavaScript: Rho.Network.headers
    • Ruby: Rho::Network.headers

This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

httpVerb : STRING

Replaces:http_command

HTTP verb to be used in the network request.

Property Access:

  • Class: This property can only be accessed via the API class object.
    • JavaScript: Rho.Network.httpVerb
    • Ruby: Rho::Network.httpVerb

This property cannot be accessed via setter or getter methods. It can be used in methods that allow a HASH or Array of properties to be passed in.

responseTimeout : INTEGER

Timeout of network requests in seconds. This property has module scope. Do not pass it as hash parameter to methods, use property accessors instead.

Default: 30

Property Access:

  • Instance: This property can be accessed via an instance object of this class:
    • myObject.responseTimeout

url : STRING

URL of the request. This should be fully formatted URL like http://domain.com/

Property Access:

  • Instance: This property can be accessed via an instance object of this class:
    • myObject.url

verifyPeerCertificate : BOOLEAN

Replaces:ssl_verify_peer

Verify SSL certificates. When set to false it will allow untrusted certificates.

Default: true

Property Access:

  • Instance: This property can be accessed via an instance object of this class:
    • myObject.verifyPeerCertificate

Examples

Request a notification from the system when network availability changes

When you need to be notified of changes in the status of the network (connected / disconnected), use Network.startStatusNotify.

    function status_notify_callback(params) {
      alert("Network status changed from "+params["prev_status"]+" to "+params["current_status"]);
    }

    function start_status_notify() {
      # Request the system to check every 3 seconds and call us back if there is a change in network connectivity
      Rho.Network.startStatusNotify(3000, status_notify_callback);
    }

    function stop_status_notify() {
      // Stop network status notifications
      Rho.Network.stopStatusNotify();
    }


                 
  def start_status_notify
    # Request the system to check every 3 seconds and call us back if there is a change in network connectivity
    Rho::Network.startStatusNotify(3000, url_for(:action => :status_notify_callback))
    Alert.show_popup "Started network status notifications"
  end

  # This is our notification that the status of the network changed. old_status and new_status can be "disconnected" or "connected"
  def status_notify_callback
    Alert.show_popup("Network status changed from #{@params["prev_status"]} to #{@params["current_status"]}")
  end


  def stop_status_notify
    # Stop network status notifications
    Rho::Network.stopStatusNotify
    Alert.show_popup "Stopped network status notifications"
  end

                 
Check whether the network is available

You can check whether the mobile, WiFi or other network is available. This can be useful for example if you only want to perform large data transfers on WiFi and avoid doing them while on the cell network.

    function network_availability() {
      // shows the network availability for...
      // Cell network
      var cell_network = Rho.Network.hasCellNetwork()
      // Wi-Fi network
      var wifi_network = Rho.Network.hasWifiNetwork()
      // Any network
      var network = Rho.Network.hasNetwork()

      alert("Cell network: "+cell_network+"\nWi-Fi network: "+wifi_network+"\nNetwork: "+network);
    }

                 
    # check the network availability for...
    # Cell network
    cell_network = Rho::Network.hasCellNetwork
    # Wi-Fi
    wifi_network = Rho::Network.hasWifiNetwork
    # Any network
    network = Rho::Network.hasNetwork

                 
Download file and save it to permanent storage

Download any file from an external server and store it in your device.

function download_file_callback(params) {
  if (params["status"] == "ok") {
    alert("Download Succeeded, path is /public/images/sample.png");
  } else {
    alert("Download Failed");
  }
}

function download_file() {
  // Download a file to the specified filename. Be careful with the overwriteFile parameter!
  downloadfileProps = {
    url: "http://www.google.com/images/icons/product/chrome-48.png",
    filename: Rho.Application.publicFolder+"/images/sample.png",
    overwriteFile: true
  };
  Rho.Network.downloadFile(downloadfileProps, download_file_callback);
}

                 
  def download_file
      #Download a file to the specified filename.
      downloadfileProps = Hash.new
      downloadfileProps["url"]='http://www.google.com/images/icons/product/chrome-48.png'
      downloadfileProps["filename"] = Rho::Application.publicFolder+"/images/sample.png"
      downloadfileProps["overwriteFile"] = true
      Rho::Network.downloadFile(downloadfileProps, url_for(:action => :download_file_callback))
  end

  def download_file_callback
    if @params["status"] == "ok"
        Alert.show_popup "Download Success,path is /public/images/sample.png "
    else
        Alert.show_popup "Download Failed"
    end
  end


                 
Upload files via HTTP POST

You can upload any file to an external server via HTTP POST and be notified whether the transfer succeeded or not.

function upload_file_callback(params) {
  // Check the result of the upload and act accordingly
  if (params["status"] == "ok") {
    alert("Upload Succeeded.");
  } else {
    alert("Upload Failed.");
  }
}

function upload_file() {
    // Upload the specified file using HTTP POST.
    uploadfileProps = {
      url: "http://www.example.com",
      filename: Rho.Application.publicFolder+"/images/backButton.png",
      body: "uploading file",
      fileContentType: "image/png"
    };

    Rho.Network.uploadFile(uploadfileProps, upload_file_callback);
}

                 
  def upload_file
    # Upload the specified file using HTTP POST.
    uploadfileProps = Hash.new
    uploadfileProps['url'] = "http://www.example.com"
    uploadfileProps['filename'] = Rho::Application.publicFolder+"/images/backButton.png"
    uploadfileProps['body'] = "uploading file"
    uploadfileProps['fileContentType']="image/png"
    Rho::Network.uploadFile(uploadfileProps, url_for(:action => :upload_file_callback))
  end

  def upload_file_callback
    if @params['status'] == "ok"
        Alert.show_popup "Upload Succeeded."
    else
        Alert.show_popup "Upload Failed."
    end
  end

                 
Network POST Using Ruby's Lambda

You can also define network request callbacks with this API using Ruby’s lambda functions, similar to how you would use a JavaScript anonymous function for a callback. Simply define your callback, using lambda, in place of the callback parameter in the method call as such.

Rho::Network.post(
  {
    url:      url,
    headers:  { 'Content-Type' => 'application/json', 'Accept' => 'application/json' },
    body:     json
  },
  lambda do |response; body, headers, cookies, http_status|

    body = response['body']
    headers = response['headers']
    cookies = response['cookies']
    http_status = response['http_status']

    app_info "TESTING got POST callback"
    app_info "body = #{body.inspect}"
    app_info "headers = #{headers.inspect}"
    app_info "cookies = #{cookies.inspect}"
    app_info "http_error = #{http_error.class} #{http_error.inspect}"
    app_info "testing lambda context, url = '#{url}'"
  end
)

                            

Remarks

Detecting a connection through proxies

Because the detectConnection method is protocol agnostic, it will not communicate through HTTP proxies to reach a specified URL. In order to determine if you are connected when sitting behind a proxy you should call the method to attempt to connect to your proxy on the appropriate port. A successful connection to the proxy should be taken to assume the device is connected to a network. When configuring your WAN connection bear in mind that the proxy settings defined in the RhoElements configuration file will take precedence.

Detecting a connection over WAN

When detecting a network connection over WAN bear in mind if you specify a low networkPollInterval your device will frequently have an active data connection and may prevent the device occasionally from accepting incoming calls.

Preventing access to the device (WEH / WM)

Receiving phone calls or texts whilst running RhoElements will cause the start button to be displayed on Windows Embedded Handheld devices, potentially offering users access to the operating system. It is recommended to set the following registry keys to disable Operating System access on Windows Embedded Handheld as required. The registry keys will be applied after a warm boot, omit them entirely to restore the Start and ‘X’ icons.

[HKEY_LOCAL_MACHINE\Software\Microsoft\Shell\BubbleTiles]   Location in Registry
"HardwareStartKeyEnabled"=dword:00000001                    Prevents the Start icon from appearing in the bottom left
"HardwareDoneKeyEnabled"=dword:00000001                     Prevents the 'X' icon from appearing in the bottom right