前段时间项目里用到了android的串口通信,网上查找资料,找到了下面一篇文章
http://lpcjrflsa.iteye.com/blog/2097280
我参考这篇文章实现了串口通信,在这里记录一下,省得以后再看的时候找不到。还有几点说明一下
1、原文使用eclipse,将android-serialport-api源码里的两个文件复制进工程里。我是用android studio,将源码直接导入到android studio里,再将app文件夹作为库添加进新项目里,具体方法前面博客已经说过了,不再赘述。
2、项目里需要android通过串口给单片机发送十六进制的指令,所以添加了hexStringToBytes()这个方法,将String类型以十六进制发送。
3、接收数据改用线程
下面是完整代码: MainActivity.java
package com.example.administrator.serialporttest; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import android_serialport_api.SerialPort; public class MainActivity extends AppCompatActivity { private Button btn_open, btn_send, btn_rec; private EditText edRec; private FileOutputStream mOutputStream; private FileInputStream mInputStream; private SerialPort sp; 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); edRec = (EditText) findViewById(R.id.edRec); btn_open = (Button) findViewById(R.id.open); btn_open.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { sp = new SerialPort(new File("/dev/ttySAC3"), 19200, 0);//这里写你要打开的串口和波特率 Toast.makeText(getApplicationContext(), "open", Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mOutputStream = (FileOutputStream) sp.getOutputStream(); mInputStream = (FileInputStream) sp.getInputStream(); } }); btn_send = (Button) findViewById(R.id.send); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { // mOutputStream.write(new String("send").getBytes()); mOutputStream.write(hexStringToBytes("AA01BB"));//这里发送的是十六进制的数据 Toast.makeText(getApplicationContext(), "send", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); btn_rec = (Button) findViewById(R.id.rec); btn_rec.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mReadThread = new ReadThread(); mReadThread.start(); } }); } void onDataReceived(final byte[] buffer, final int size) { runOnUiThread(new Runnable() { public void run() { if (edRec != null) { edRec.append(new String(buffer, 0, size)); } } }); } public static byte[] hexStringToBytes(String inputStr) { byte[] result = new byte[inputStr.length() / 2]; for (int i = 0; i < inputStr.length() / 2; ++i) result[i] = (byte) (Integer.parseInt(inputStr.substring(i * 2, i * 2 + 2), 16) & 0xff); return result; } @Override protected void onDestroy() { if (mReadThread != null) mReadThread.interrupt(); sp = null; super.onDestroy(); } }activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.administrator.serialporttest.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/open" android:text="open"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/send" android:text="send"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/rec" android:text="rec"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/edRec"/> </LinearLayout> </LinearLayout>界面设计和原文差不多,我就不放图了
下面是完整项目地址
http://download.csdn.net/detail/amazinguu/9630474
P.S:附上一个bytesToHexString()方法,可以用来处理android通过串口接收单片机发送的十六进制数据
public static String bytesToHexString(byte[] buffer){ String result=""; for (int i = 0; i < buffer.length; i++) { String hex = Integer.toHexString(buffer[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } result=result+hex;//result字符串长度为2的倍数 } return result; }