Open a network connection using the GCF

The following task shows you how to open an HTTP connection using the BlackBerry® Mobile Data System transport. You can use a similar process to open a connection using other protocols and transports.
CAUTION:
The Connector.open() method is not thread-safe. Ensure that you invoke open() on a thread that is separate from the main event thread.
Before you begin: Make sure that the transport that you want to use is available and has coverage.
  1. Import the required classes and interfaces.
    import net.rim.device.api.ui.UiApplication;
    import java.io.IOException;
    import javax.microedition.io.*;
  2. Create a new thread to open the connection.
    Thread t = new Thread(new Runnable()
    {
        public void run()
        {
  3. Create a local variable for your Connection object.
            Connection conn = null;
  4. Invoke open(). Specify the connection string.
            try
            {
                conn = Connector.open("http://www.blackberry.com;deviceside=false");
            } catch (IOException e)
            {
                // Process your error condition
            }
  5. If the connection attempt was successful, open() returns a Connection object that you can use. Pass the connection object to another method (displayContent()) that is responsible for displaying the content.
            if (conn != null)
            {
                displayContent(conn);
            }
        }
    });
  6. Start your thread.
    t.start();
  7. Implement displayContent(). In this case, push a screen that uses a Connection parameter to retrieve and display the content, after the connection retrieval thread completes.
    private void displayContent(final Connection conn) 
    {
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run() {
                UiApplication.getUiApplication().pushScreen(new HTTPOutputScreen(conn));
            }
        });
    }
After you finish: For more information about using a connection, and implementing the HTTPOutputScreen class, see "Send and receive data using a network connection".

For a complete code sample, see "Code sample: Retrieving a web page using the GCF".


Was this information helpful? Send us your comments.