安卓串口通訊三

核心代碼如下:

java 复制代码
package com.example.comandroid;

import static android.content.ContentValues.TAG;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.jackiepenghe.serialportlibrary.MultipleSerialPortManager;
import com.jackiepenghe.serialportlibrary.OnSerialPortDataChangedListener;
import com.jackiepenghe.serialportlibrary.SerialPortManager;
import com.sscl.baselibrary.utils.ConversionUtil;
import com.sscl.baselibrary.utils.DebugUtil;
import com.sscl.baselibrary.utils.ToastUtil;

import java.nio.charset.Charset;

/**
* 功能描述:
* 版权所有:
* 版本:1.0
* 作者:
* 创建时间 ${DATE} ${hour}
* 邮箱 :2848444745@qq.com
*
*/

public class MainActivity extends AppCompatActivity {
    private Button btnOpen;
    private Button btnClose;
    private Button btnSend;
    private TextView text;
    private String serialPort="/dev/ttyS1";//串口路徑
//    private String serialPort="/dev/ttyS2";//串口路徑
//    private String serialPort="/dev/ttyS3";//串口路徑
//    private String serialPort="/dev/ttyS4";//串口路徑
    private int baudRate = 9600;//波特率
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnClose=findViewById(R.id.btn_close);
        btnOpen=findViewById(R.id.btn_open);
        btnSend=findViewById(R.id.btn_send);
        text=findViewById(R.id.textView);

        //打開串口
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSerialPort();
            }
        });

        //關閉串口
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultipleSerialPortManager.closeSerialPort(serialPort);
            }
        });
        //發送數據
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData("發送測試");
            }
        });

    }

    /**
     * 串口监听
     */
    private final OnSerialPortDataChangedListener onSerialPortDataChangedListener = (data, size) -> {
        byte[] cache = new byte[size];
        System.arraycopy(data, 0, cache, 0, size);
        DebugUtil.warnOut(TAG, "cache = " + ConversionUtil.byteArrayToHexStr(cache));
        DebugUtil.warnOut(TAG, "cache = " + new String(cache));
        String result = ConversionUtil.byteArrayToHexStr(cache);
        text.setText(result);


    };

    /**
     * 打开串口
     */
    private void openSerialPort() {
        boolean open = MultipleSerialPortManager.openSerialPort(serialPort, baudRate, onSerialPortDataChangedListener);
        if (open) {
            ToastUtil.toastLong(this, "串口打開成功");
            DebugUtil.warnOut(TAG, "串口打開成功");
            this.serialPort = serialPort;
        } else {
            DebugUtil.warnOut(TAG, "串口打開失敗");
            ToastUtil.toastLong(this, "串口打開失敗");
        }


    }

    /**
     * 获取串口信息
     */
    private void getSerialPortInfo() {
        String[] allDevices = MultipleSerialPortManager.getAllDevices();
        if (allDevices.length == 0) {
            DebugUtil.warnOut(TAG, "allDevices length == 0");
        }
        for (int i = 0; i < allDevices.length; i++) {
            DebugUtil.warnOut(TAG, "allDevices[" + i + "] = " + allDevices[i]);
        }
        String[] allDevicesPath = MultipleSerialPortManager.getAllDevicesPath();
        if (allDevicesPath.length == 0) {
            DebugUtil.warnOut(TAG, "allDevicesPath length == 0");
        }
        for (int i = 0; i < allDevicesPath.length; i++) {
            DebugUtil.warnOut(TAG, "allDevicesPath[" + i + "] = " + allDevicesPath[i]);
        }

    }

   // 关闭串口
    private void closeSerialPort() {
        if (serialPort == null) {
            return;
        }
        MultipleSerialPortManager.closeSerialPort(serialPort);
    }

    // 發送數據
    private void sendData(String data) {
        boolean succeed= MultipleSerialPortManager.writeData(serialPort, "1234567890", Charset.forName("UTF-8"));
        if (!succeed){
            ToastUtil.toastLong(this, "發生失敗");
        }else{
            ToastUtil.toastLong(this, "發送成功");
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeSerialPort();
    }
}

想要完整的了解,可以看下完整的dome,這我也給出來了完整dome如下:

https://download.csdn.net/download/qq_41733851/89288862?spm=1001.2014.3001.5503

相关推荐
xvch2 小时前
Kotlin 2.1.0 入门教程(二十三)泛型、泛型约束、协变、逆变、不变
android·kotlin
ianozo3 小时前
BUU40 [安洵杯 2019]easy_serialize_php
android·开发语言·php
abs6253 小时前
uniapp使用uts插件启动原生安卓Service
android·uni-app·uniapp uts插件·uniapp 安卓服务
Evaporator Core3 小时前
MATLAB在投资组合优化中的应用:从基础理论到实践
android
Neo Evolution4 小时前
Flutter与移动开发的未来:谷歌的技术愿景与实现路径
android·人工智能·学习·ios·前端框架·webview·着色器
coooliang4 小时前
Flutter项目中设置安卓启动页
android·flutter
xianrenli384 小时前
android 使用 zstd算法压缩文件
android
九思x5 小时前
Android Studio安装配置及运行
android·ide·android studio
风浅月明16 小时前
[Android]如何判断当前APP是Debug还是Release环境?
android
freflying111916 小时前
使用jenkins构建Android+Flutter项目依赖自动升级带来兼容性问题及Jenkins构建速度慢问题解决
android·flutter·jenkins