4

我正在用 Java 编写一个程序来发送和接收 SMS 文本消息。我正在使用 AT 命令和我的诺基亚设备的蓝牙连接。我写了一个类来发送消息。但我不知道如何让 java 串行事件在我收到短信时通知我。

为了在我向手机写入适当的 AT 命令时接收消息,然后我编写了一个类,每 10 秒向手机发送一个换行语句,这会显示任何新消息。

我真的更喜欢使用串行事件处理传入的消息。任何有关如何执行此操作或 Java 代码的信息将不胜感激。

4

1 回答 1

1

Take a look at org.smslib: http://smslib.org/

Example use of that library here: https://groups.google.com/forum/#!topic/smslib/6b4dR5pJjBY

Alternatively, if you really need to do it using javax.commm alone - some example code to get you started is here:

http://www.java2s.com/Code/JavaAPI/javax.comm/SerialPortaddEventListenerSerialPortEventListenerarg0.htm

In particular:

You need to call SerialPort.addEventListener(SerialPortEventListener arg0) and then serialPort.notifyOnDataAvailable(true);

When this is setup you can then act on SerialPortEventListener's callback like so:

public void serialEvent(SerialPortEvent event) {
  switch (event.getEventType()) {
  case SerialPortEvent.BI:
  case SerialPortEvent.OE:
  case SerialPortEvent.FE:
  case SerialPortEvent.PE:
  case SerialPortEvent.CD:
  case SerialPortEvent.CTS:
  case SerialPortEvent.DSR:
  case SerialPortEvent.RI:
  case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    break;
  case SerialPortEvent.DATA_AVAILABLE:
    byte[] readBuffer = new byte[20];

    try {
      while (inputStream.available() > 0) {
        int numBytes = inputStream.read(readBuffer);
      }   
      System.out.print(new String(readBuffer));
    } catch (IOException e) {
    }   
    break;
  }   
}
于 2015-04-20T21:43:53.503 回答