欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

android即时通讯demo开源(android studio实现聊天功能)

程序员文章站 2023-11-17 14:02:52
android串口通信可以实现设备与设备之间通过设备线连接进行数据(消息)传递(一)导入so库(二)在moudle的build中添加jnilibsbuildtypes { sources...

android串口通信可以实现设备与设备之间通过设备线连接进行数据(消息)传递
(一)导入so库

android即时通讯demo开源(android studio实现聊天功能)


(二)在moudle的build中添加jnilibs

buildtypes {
        sourcesets {
            main { jni.srcdirs = [] }
        }
    }
12345

(三)添加google的serialport
添加的是google的所以必须创建android_serialport_api包
如需要更改serialport、serialportfinder位置需要重新生成so库

android即时通讯demo开源(android studio实现聊天功能)

(四)创建串口通信工具类serialportutils

package com.demo.serialport;

import android.util.log;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import android_serialport_api.serialport;

/**
 * @author renquan
 */

public class serialportutils {

    private final string tag = "serialportutils";
//    private string path = "/dev/ttys1";
//    private int baudrate = 9600;
    public boolean serialportstatus = false; //是否打开串口标志
    public string data_;
    public boolean threadstatus; //线程状态,为了安全终止线程

    public serialport serialport = null;
    public inputstream inputstream = null;
    public outputstream outputstream = null;
    public changetool changetool = new changetool();


    /**
     * 打开串口
     * @return serialport串口对象
     */
    public serialport openserialport(string path,int baudrate){
        try {
            serialport = new serialport(new file(path),baudrate,0);
            this.serialportstatus = true;
            threadstatus = false; //线程状态

            //获取打开的串口中的输入输出流,以便于串口数据的收发
            inputstream = serialport.getinputstream();
            outputstream = serialport.getoutputstream();

            new readthread().start(); //开始线程监控是否有数据要接收
        } catch (ioexception e) {
            log.e(tag, "openserialport: 打开串口异常:" + e.tostring());
            return serialport;
        }
        log.d(tag, "openserialport: 打开串口");
        return serialport;
    }

    /**
     * 关闭串口
     */
    public void closeserialport(){
        try {
            inputstream.close();
            outputstream.close();

            this.serialportstatus = false;
            this.threadstatus = true; //线程状态
            serialport.close();
        } catch (ioexception e) {
            log.e(tag, "closeserialport: 关闭串口异常:"+e.tostring());
            return;
        }
        log.d(tag, "closeserialport: 关闭串口成功");
    }

    /**
     * 发送串口指令(字符串)
     * @param data string数据指令
     */
    public void sendserialport(string data){
        log.d(tag, "sendserialport: 发送数据");

        try {
            byte[] senddata = data.getbytes(); //string转byte[]
            this.data_ = new string(senddata); //byte[]转string
            if (senddata.length > 0) {
                outputstream.write(senddata);
                outputstream.write('n');
                //outputstream.write('r'+'n');
                outputstream.flush();
                log.d(tag, "sendserialport: 串口数据发送成功");
            }
        } catch (ioexception e) {
            log.e(tag, "sendserialport: 串口数据发送失败:"+e.tostring());
        }

    }

    /**
     * 单开一线程,来读数据
     */
    private class readthread extends thread{
        @override
        public void run() {
            super.run();
            //判断进程是否在运行,更安全的结束进程
            while (!threadstatus){
                log.d(tag, "进入线程run");
                //64   1024
                byte[] buffer = new byte[64];
                int size; //读取数据的大小
                try {
                    size = inputstream.read(buffer);
                    if (size > 0){
                        log.d(tag, "run: 接收到了数据:" + changetool.bytearrtohex(buffer));
                        log.d(tag, "run: 接收到了数据大小:" + string.valueof(size));
                        ondatareceivelistener.ondatareceive(buffer,size);
                    }
                } catch (ioexception e) {
                    log.e(tag, "run: 数据读取异常:" +e.tostring());
                }
            }

        }
    }

    //数据回调
    public ondatareceivelistener ondatareceivelistener = null;
    public static interface ondatareceivelistener {
        public void ondatareceive(byte[] buffer, int size);
    }
    public void setondatareceivelistener(ondatareceivelistener datareceivelistener) {
        ondatareceivelistener = datareceivelistener;
    }

}

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
package com.demo.serialport;

/**
 * @author renquan
 */

public class changetool {

    /**
     * byte数组转16进制字符串
     *
     * @param bytes byte数组
     * @return 16进制字符串
     */
    public string bytearrtohex(byte[] bytes) {
        string strhex;
        stringbuilder sb = new stringbuilder();
        for (byte abyte : bytes) {
            strhex = integer.tohexstring(abyte & 0xff);
            sb.append(" ").append((strhex.length() == 1) ? "0" : "").append(strhex); // 每个字节由两个字符表示,位数不够,高位补0
        }
        return sb.tostring().trim();
    }

    /**
     * byte字节转int
     *
     * @param b byte字节
     * @return int
     */
    public static int bytetoint(byte b) {
        int x = b & 0xff;
        if (x == 127) {
            return 0;
        }
        return x;
    }
}

123456789101112131415161718192021222324252627282930313233343536373839
package com.demo.serialport;

import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.button;
import android.widget.edittext;

import androidx.appcompat.app.appcompatactivity;

/**
 * @author renquan
 */

public class mainactivity extends appcompatactivity implements view.onclicklistener {
    private edittext mmessage;
    private button mopen;
    private button msend;
    private button mclose;
    private serialportutils serialportutils;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        init();


        //串口数据监听事件
        serialportutils.setondatareceivelistener(new serialportutils.ondatareceivelistener() {
            @override
            public void ondatareceive(byte[] buffer, int size) {
                log.d("tag", "进入数据监听事件中。。。" + new string(buffer));

            }
        });

    }

    private void init() {
        initview();
        serialportutils = new serialportutils();
    }

    private void initview() {
        mmessage = (edittext) findviewbyid(r.id.message);
        mopen = (button) findviewbyid(r.id.open);
        mopen.setonclicklistener(this);
        msend = (button) findviewbyid(r.id.send);
        msend.setonclicklistener(this);
        mclose = (button) findviewbyid(r.id.close);
        mclose.setonclicklistener(this);
    }

    @override
    public void onclick(view v) {
        switch (v.getid()) {
            case r.id.open:
                // todo 20/12/28
                serialportutils.openserialport("/dev/ttys9",9600);
                break;
            case r.id.send:
                // todo 20/12/28
                serialportutils.sendserialport(msend.gettext().tostring());
                break;
            case r.id.close:
                serialportutils.closeserialport();
                // todo 20/12/28
                break;
            default:
                break;
        }
    }
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374

demo——github地址