主要java代码
- 对android串口的接受与发送的主要java代码:
private SerialPort mSerialPort;
private OutputStream outputStream;
private InputStream inputStream;
private ReadThread readThread;
String serialPath = "/dev/ttyS0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mSerialPort = new SerialPort(new File(serialPath), 9600, 0);
outputStream = mSerialPort.getOutputStream();
inputStream = mSerialPort.getInputStream();
readThread = new ReadThread();
readThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
int maxLength = 2048;
byte[] buffer = new byte[maxLength];
int size;
while (!isInterrupted()) {
try {
if(inputStream.available() > 0) {
SystemClock.sleep(200);
size = inputStream.read(buffer);
if (size > 0) {
onDataReceived(buffer, size);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onDataReceived(byte[] buffer, int size) {
byte START_BYTE = (byte) 0xFE;
if (buffer[0] == START_BYTE){
byte END_BYTE2 = (byte) 0xBB;
byte END_BYTE1 = (byte) 0xBB;
if (buffer[size-2] == END_BYTE1 && buffer[size-1] == END_BYTE2) {
}
}
}
try {
int getIpFour = Integer.parseInt(listAtBack.get(i).split(",")[5].split("\\.")[3]);
int snr = Integer.parseInt(listAtBack.get(i).split(",")[10].replace("\"",""));
byte[] sumBuffer = new byte[] {(byte)0xFE, (byte)getIpFour, (byte)snr};
short sumCheck = Util.sumCheck(sumBuffer);
byte[] mBuffer = new byte[]{};
String binary = Integer.toString(sumCheck,2);
int targetLength = 16;
if (binary.length()<targetLength) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j<targetLength - binary.length(); j++) {
sb.append("0");
}
String newBinary = sb + binary;
int decimal1 = Integer.parseInt(newBinary.substring(0,8),2);
int decimal2 = Integer.parseInt(newBinary.substring(8,16),2);
mBuffer = new byte[] {(byte)0xFE, (byte)getIpFour, (byte)snr, (byte)decimal1, (byte)decimal2, (byte)0xBB, (byte)0xBB} ;
}
if (outputStream != null) {
if (mBuffer.length == 7) {
outputStream.write(mBuffer);
}
}
} catch (Exception e ) {
e.printStackTrace();
}
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />