Actually I'm trying to open serial port to send logging data in j2me.
When I connect my phone via usb cable to pc my code works correctly. But when I start app without usb cable connecting to phone it is hanging up.

private static void sendToSerial(String msg) {
        try {
            if (msg == null) return;
            msg += getEol(); // append End Of Line symbol "\r\n"
            CommConnection comm = (CommConnection)Connector.open("comm:" + getComPort());
            OutputStream os = comm.openOutputStream();
            os.write(msg.getBytes());
            os.close();
            comm.close();
        } catch (Exception error) {
            error.printStackTrace();
        }
    }

in above code getComPort() returns "com0" string.

Is there any way to use Connector.open() with timeout?
I already tried this too:

comm = (CommConnection)Connector.open("comm:" + getComPort(), Connector.WRITE, true);

Or is there any way to detect serial port is available or not?
I've already analyze microedition.commports system property too. Following method gives me "COM0" value.

public static String getComPort() {
        if (comPort != null && comPort.trim().length() > 0) {
            return comPort;
        }
        String comPorts = System.getProperty("microedition.commports");
        if (comPorts != null && comPorts.toLowerCase().indexOf("com") != -1) {
            int idxStart = comPorts.toLowerCase().indexOf("com");
            comPort = comPorts.substring(idxStart, idxStart + 4);
        }
        //midlet.showAlert("com port = " + comPort);
        return comPort;
    }

Dani AI

Generated

Quick summary tied to @neo's posts: the J2ME property microedition.commports only lists logical port names (COM0, IR0, USB0, etc.), it does not guarantee a physical cable is attached or that opening the port will be fast. On many phones COM means the cable interface, so trying to open it with no cable can block or fail. (docs.oracle.com)

Practical, portable approach:

  • Never call Connector.open() on the UI/main event thread — do the open on a worker thread so the UI won’t freeze if the call blocks. Some implementations will honor the timeouts hint to Connector.open(..., true) and/or a Timeout ConnectionOption; others ignore it, so code must handle both cases. On Java ME 8+ you can pass a ConnectionOption("Timeout", ms) to request a connect timeout; if the runtime supports it you’ll get an InterruptedIOException you can catch. (nikita36078.github.io)

Example pattern (keep it off the UI thread; Java ME 8 shown — fall back to a plain worker thread on older devices):

Thread t = new Thread() {
  public void run() {
    try {
      ConnectionOption<Integer> to = new ConnectionOption<Integer>("Timeout", new Integer(5000));
      CommConnection cc = (CommConnection)Connector.open("comm:COM0;baudrate=19200",
                                                         Connector.WRITE, true, to);
      // write, close
      cc.close();
    } catch (InterruptedIOException iio) {
      // timed out -> treat as unavailable
    } catch (IOException ioe) {
      // COM busy or other I/O error
    }
  }
};
t.start();

Why the TimerTask trick failed: TimerTask.cancel() (or canceling the Timer) does not stop a task that is already running, and Thread.interrupt() does not reliably abort native blocking I/O — the safe options are to rely on an implementation timeout, close the underlying connection (when possible), or keep the open off the UI thread and treat long-running attempts as "unavailable". Where supported, try ;blocking=off or vendor-specific URL parameters, and consult the handset/vendor docs for the correct logical port names (many devices map ports differently). (download.java.net)

Key takeaways: open comm ports in a worker thread, request timeouts where supported (ConnectionOption), always catch I/O exceptions (COM busy), and prefer a user action or explicit cable-detection strategy rather than opening serial ports automatically at startup.

I've also tried achieve this code snippet, which uses two TimerTask: first one for connecting to com port, second one starts a bit later to canceling first timer task if it hasn't finished work.

private static CommConnection comm = null;
    private static Timer timer1 = null;
    private static Timer timer2 = null;
    private static ComConnectTask connectTask = null;
    private static ComCancelTask cancelTask = null;
    private static boolean isComAvailable = false;
     ...
    /**
     * Tries to connect to com port.
     * @return true, if connection success. Otherwise returns false.
     */
    private static boolean connect() {
        isComAvailable = false;
        timer1 = new Timer();
        timer2 = new Timer();
        connectTask = new ComConnectTask();
        cancelTask = new ComCancelTask();
        timer1.schedule(connectTask, new Date());
        timer2.schedule(cancelTask, 5000);
        return isComAvailable;
    }
    
    /**
     * Task for connecting to com port.
     */
    private static class ComConnectTask extends TimerTask {
        public void run() {
            try {
                comm = (CommConnection)Connector.open("comm:" + getComPort(), Connector.WRITE, true);
                isComAvailable = true;
            } catch (Exception error) {
                error.printStackTrace();
            }
        }
    }
    
    /**
     * Task for canceling connection task to com port.
     */
    private static class ComCancelTask extends TimerTask {
        public void run() {
            if (!isComAvailable) {
                connectTask.cancel();
            }
        }
    }

it throws IOException: COM busy.
Please, help me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.