Problemas httpconnection + wtk21 + emulador

Olá pessoal,

Estou tentando rodar o codigo abaixo no Emulador que vem com o WTK 2.1 porem não estou tendo sucesso.
O arquivo que estou tentando baixar é pequeno (1k)

Quando tento rodar ele dá um aviso na tela do emulador:

Is ok to use airtime ?

Botões Yes e No aparecem. Clico no Yes porem nada acontece !

e o seguinte Warning no console

Warning: To avoid potential deadlock, operations that may block, such as
networking, should be performed in a different thread than the
commandAction() handler.

Até entendi que o warning sugere o uso de um Thread para a conexao mas isso impede a execução do mesmo ?

Obrigado desde já,

Spiff

/*--------------------------------------------------
* FileViewer.java - Exemplo do livro CoreJ2ME
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class FileViewer extends MIDlet implements CommandListener
{
  private Display display;
  private Form fmMain;
  private Command cmExit;
  private Command cmView;
  private String url = "http://xxxxxxx/teste.txt";

  public FileViewer()
  {
    display = Display.getDisplay(this);

    // Create exitcommand
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmView = new Command("View", Command.SCREEN, 2);

    // Create the form and add commands
    fmMain = new Form("File Viewer");
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmView);

    fmMain.setCommandListener(this);
  }

  public void startApp()
  {
    display.setCurrent(fmMain);
  }

  /*--------------------------------------------------
  * Process events
  *-------------------------------------------------*/
  public void commandAction(Command c, Displayable s)
  {
    // If the Command button pressed was "Exit"
    if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (c == cmView)
    {
      // Download image and place on the form
      try
      {
        String str;
        if ((str = readFile()) != null)
        {
          // Delete form contents
          for (int i = fmMain.size(); i > 0; i--)
            fmMain.delete(0);

          // Append downloaded string
          fmMain.append("" + str);
        }
      }
      catch (Exception e)
      {
        System.err.println("Msg: " + e.toString());
      }
    }
  }

  /*--------------------------------------------------
  * Read file
  *-------------------------------------------------*/
  private String readFile() throws IOException
  {
    HttpConnection http = null;
    InputStream iStrm = null;
    String str = null;

    try
    {
      // Create the connection
      http = (HttpConnection) Connector.open(url);

      //----------------
      // Client Request
      //----------------
      // 1) Send request method
      http.setRequestMethod(HttpConnection.GET);

      // 2) Send header information (this header is optional)
      http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");

      // 3) Send body/data - No data for this request


      //----------------
      // Server Response
      //----------------
      System.out.println("url: " + url);
      System.out.println("-------------------------");

      // 1) Get status Line
      System.out.println("Msg: " + http.getResponseMessage());
      System.out.println("Code: " + http.getResponseCode());
      System.out.println("-------------------------");

      // 2) Get header information
      if (http.getResponseCode() == HttpConnection.HTTP_OK)
      {
        System.out.println("key 0: " + http.getHeaderFieldKey(0));
        System.out.println("key 1 : " + http.getHeaderFieldKey(1));
        System.out.println("key 2: " + http.getHeaderFieldKey(2));
        System.out.println("-------------------------");

        System.out.println("value (field) 0: " + http.getHeaderField(0));
        System.out.println("value (field) 1: " + http.getHeaderField(1));
        System.out.println("value (field) 2: " + http.getHeaderField(2));
        System.out.println("-------------------------");

        // 3) Get data (show the file contents)
        iStrm = http.openInputStream();
        int length = (int) http.getLength();
        if (length != -1)
        {
          // Read data in one chunk
          byte serverData[] = new byte[length];
          iStrm.read(serverData);
          str = new String(serverData);
        }
        else  // Length not available...
        {
          ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

          // Read data one character at a time
          int ch;
          while ((ch = iStrm.read()) != -1)
            bStrm.write(ch);

          str = new String(bStrm.toByteArray());
          bStrm.close();
        }

        //-----------------------------
        // Show connection information
        //-----------------------------
        System.out.println("Host: " + http.getHost());
        System.out.println("Port: " + http.getPort());
        System.out.println("Type: " + http.getType());
      }
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (http != null)
        http.close();
    }

    return str;

  }

  public void pauseApp()
  { }

  public void destroyApp(boolean unconditional)
  {
  }
}

pessoal,

só para registrar…

Testei esse exemplo em um celular e funcionou !!

Fiz um teste com o exemplo usando Thread e funcionou ! Não testei ainda no celular…

Alguem saberia dizer se isso é uma restrição no emulador e em algum aparelho ?

valeu,

Spiff

Olha, a mensagem que você recebeu, não é um erro, apenas um aviso.

Ademais, você pode fazer suas aplicações tanto single-threaded com multi-threaded.

O ideal seria multi, até para que você evite da sua aplicação ficar tão ocupada que impeça o usuário de cancelar uma conexão, por exemplo.

[quote=“boone”]Olha, a mensagem que você recebeu, não é um erro, apenas um aviso.

Ademais, você pode fazer suas aplicações tanto single-threaded com multi-threaded.

O ideal seria multi, até para que você evite da sua aplicação ficar tão ocupada que impeça o usuário de cancelar uma conexão, por exemplo.[/quote]

boone,

tinha entendido sobre o warning…

o problema é o pq da aplicação não funcionar em single-threaded… somente em multi-threaded… isso no emulador… pois testei em um cel (mot a388) e funcionou… mas é complicado desenvolver sem o emulador…

valeu !

spiff

Bem,

este tipo de problema eu nunca tive.

Uma vez desenvolvi uma midlet muito besta mesmo, só para testar HttpConnection e ela era single-threaded.
Funcionou sem problemas. É lógico que os botões de comando não responderam enquanto a requisição HTTP não se findou…

No emulador funciona dos dois jeitos (single e multi).

Nunca tive problema com isto.