10. To receive data on the datgram connection, invoke
receive()
on the datagram connection. The
receive()
method
blocks other operations until it receives a data packet. Use a timer to retransmit the request or close the connection if a
reply does not arrive.
byte[] buf = new byte[256];
Datagram inDatagram = conn.newDatagram(buf, buf.length);
conn.receive(inDatagram);
11.
To extract data from a datagram, invoke
getData()
. If you know the type of data that you are receiving, convert the
data to the appropriate format.
String received = new String(inDatagram.getData());
12. Close the datagram connection, invoke
close()
on the input and output streams, and on the datagram connection
object.
conn.close();
Use a USB or serial port connection
Using a serial or USB connection, BlackBerry® device applications can communicate with desktop applications when they are
connected to a computer using a serial or USB port. This type of connection also lets BlackBerry device applications communicate
with a peripheral device that plugs into the serial or USB port.
1.
Import the following classes:
•
javax.microedition.io.Connector
•
java.io.DataOutputStream
•
java.lang.String
•
java.io.DataInputStream
2.
Import the
javax.microedition.io.StreamConnection
interface.
3.
Invoke
Connector.open()
, and specify
comm
as the protocol and COM1 or USB as the port to open a USB or serial
port connection, .
private StreamConnection _conn = (StreamConnection)Connector.open(
"comm:COM1;baudrate=9600;bitsperchar=8;parity=none;stopbits=1");
4.
To send data on the USB or serial port connection, invoke
openDataOutputStream()
or
openOutputStream()
.
DataOutputStream _dout = _conn.openDataOutputStream();
5.
Use the write methods on the output stream to write data.
private String data = "This is a test";
_dout.writeChars(data);
6.
To receive data on the USB or serial port connection, use a non-main event thread to read data from the input stream.
Invoke
openInputStream()
or
openDataInputStream()
.
DataInputStream _din = _conn.openInputStream();
Use the read methods on the input stream to read data.
Development Guide
Connections
60