public class MainActivity extends Activity { private SerialPort mSerialPort; private OutputStream mOutputStream; private InputStream mInputStream; private ReadThread mReadThread;
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while (!isInterrupted()) {
int size;
try {
byte[] buffer = new byte[64];
if (mInputStream == null) return;
size = mInputStream.read(buffer);
if (size > 0) {
onDataReceived(buffer, size);
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openSerialPort();
}
private void openSerialPort() {
try {
mSerialPort = new SerialPort(new File("/dev/ttyS0"), 115200, 0);
mOutputStream = mSerialPort.getOutputStream();
mInputStream = mSerialPort.getInputStream();
mReadThread = new ReadThread();
mReadThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//将接收到的数据进行处理
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
closeSerialPort();
}
private void closeSerialPort() {
mReadThread.interrupt();