最近好多做安卓端跟硬件交互的,比如一些智能家居,販賣機(jī)的。
而這些不管是485也好,232的板子也好,都會用到串口通訊,去往下位機(jī)發(fā)送指令操控。下面是我個(gè)人的一些理解,發(fā)送串口指令的方法都是一樣的,各位用的時(shí)候直接拷貝過去,改一下波特率和串口號就可以測試了。
總代碼:一個(gè)activity,兩個(gè)工具類,一個(gè)聲明全局變量的類,布局有一個(gè)edit發(fā)送指令,一個(gè)發(fā)送按鈕,一個(gè)接收數(shù)據(jù)顯示的textview
至于jni的一些文件夾和一些so文件就要自己去弄了,
activity的xml布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_main_input"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@drawable/cycle_corner_border"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:paddingLeft="8dp"
android:hint="輸入的指令"/>
<Button
android:id="@+id/btn_main_send"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="發(fā)送"/>
<TextView
android:id="@+id/tv_main_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="這里顯示接收到的串口數(shù)據(jù)"/>
</LinearLayout>
MainActivity:
public class MainActivity extends Activity {
private EditText editInput;
private Button btnSend;
private static TextView textShow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
/**
* 初始化UI控件
*/
private void init() {
editInput = findViewById(R.id.et_main_input);
btnSend = findViewById(R.id.btn_main_send);
textShow = findViewById(R.id.tv_main_show);
//打開串口
SerialPortUtil.openSrialPort();
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSend();//點(diǎn)擊發(fā)送調(diào)用onSend
}
});
}
/**
* 發(fā)送串口數(shù)據(jù)
*/
private void onSend() {
String input = editInput.getText().toString();
if(TextUtils.isEmpty(input)){
editInput.setError("要發(fā)送的數(shù)據(jù)不能為空");
return;
}
//發(fā)送指令
SerialPortUtil.sendSerialPort(input);
}
/**
* 刷新UI界面
* @param data 接收到的串口數(shù)據(jù)
*/
public static void refreshTextView(String data){
Log.i(TAG, "refreshTextView: "+strTo16(data));//打印接收到的數(shù)據(jù)
textShow.setText(textShow.getText().toString()+";"+strTo16(data));
}
/**
* 字符串轉(zhuǎn)化成為16進(jìn)制字符串
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
}
SerialPortUtil工具類
public class SerialPortUtil {
public static SerialPort serialPort = null;
public static InputStream inputStream = null;
public static OutputStream outputStream = null;
public static Thread receiveThread = null;
public static boolean flag = false;
public static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
/**
* 打開串口的方法
*/
public static void openSrialPort(){
Log.i("test","打開串口");
try {
serialPort = new SerialPort(new File("/dev/"+ IConstant.PORT),IConstant.BAUDRATE,0);
//獲取打開的串口中的輸入輸出流,以便于串口數(shù)據(jù)的收發(fā)
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
flag = true;
receiveSerialPort();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*關(guān)閉串口的方法
* 關(guān)閉串口中的輸入輸出流
* 然后將flag的值設(shè)為flag,終止接收數(shù)據(jù)線程
*/
public static void closeSerialPort(){
Log.i("test","關(guān)閉串口");
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
flag = false;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 發(fā)送串口數(shù)據(jù)的方法
* @param data 要發(fā)送的數(shù)據(jù)
*/
public static void sendSerialPort(String data){
Log.i("test","發(fā)送串口數(shù)據(jù)");
try {
byte[] sendData = data.getBytes();
outputStream.write(sendData);
outputStream.flush();
Log.i(TAG, "sendSerialPort: "+sendData);
Log.i("test","串口數(shù)據(jù)發(fā)送成功");
} catch (IOException e) {
e.printStackTrace();
Log.i("test","串口數(shù)據(jù)發(fā)送失敗");
}
}
/**
* 接收串口數(shù)據(jù)的方法
*/
public static void receiveSerialPort(){
Log.i("test","接收串口數(shù)據(jù)");
if(receiveThread != null)
return;
/*定義一個(gè)handler對象要來接收子線程中接收到的數(shù)據(jù)
并調(diào)用Activity中的刷新界面的方法更新UI界面
*/
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
MainActivity.refreshTextView(msg.getData().getString("data"));
}
};
/*創(chuàng)建子線程接收串口數(shù)據(jù)
*/
receiveThread = new Thread(){
@Override
public void run() {
while (flag) {
try {
byte[] readData = new byte[1024];
if (inputStream == null) {
return;
}
int size = inputStream.read(readData);
if (size>0 && flag) {
String recinfo = new String(readData,0,size);
Log.i("test", "接收到串口數(shù)據(jù):" + recinfo);
/*將接收到的數(shù)據(jù)封裝進(jìn)Message中,然后發(fā)送給主線程
*/
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("data",recinfo);
message.setData(bundle);
handler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
//啟動(dòng)接收線程
receiveThread.start();
}
}
SerialPort類
public class SerialPort {
private static final String TAG = "SerialPort";
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
//檢查訪問權(quán)限,如果沒有讀寫權(quán)限,進(jìn)行文件操作,修改文件訪問權(quán)限
if (!device.canRead() || !device.canWrite()) {
try {
//通過掛載到linux的方式,修改文件的操作權(quán)限
Process su = Runtime.getRuntime().exec("/system/xbin/su");
String cmd = "chmod 777 " + device.getAbsolutePath() + "\n" + "exit\n";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
mFd = open(device.getAbsolutePath(), baudrate, flags);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}
public OutputStream getOutputStream() {
return mFileOutputStream;
}
// JNI(調(diào)用java本地接口,實(shí)現(xiàn)串口的打開和關(guān)閉)
/**串口有五個(gè)重要的參數(shù):串口設(shè)備名,波特率,檢驗(yàn)位,數(shù)據(jù)位,停止位
其中檢驗(yàn)位一般默認(rèn)位NONE,數(shù)據(jù)位一般默認(rèn)為8,停止位默認(rèn)為1*/
/**
* @param path 串口設(shè)備的據(jù)對路徑
* @param baudrate 波特率
* @param flags 校驗(yàn)位
*/
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {//加載jni下的C文件庫
System.loadLibrary("serial_port");
}
}
IConstant
public interface IConstant {
String PORT = "填寫你那邊需要連接的串口號";//串口號
int BAUDRATE = ;//波特率
}