Android蓝牙开发(三)之蓝牙通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huangliniqng/article/details/82189735

上篇文章:https://blog.csdn.net/huangliniqng/article/details/82187966

上篇文章我们讲解了,蓝牙配对和蓝牙连接相关知识,还没有了解的朋友可先移步上篇文章。

1.蓝牙通信简介

  无论是做Java还是Android开发的朋友肯定都比较熟悉Socket的连接,在java中通信用的是Socket,同样的蓝牙之间通信(这里说的是经典蓝牙)方式也是Socket,只不过是BluetoothSocket,同样的也要有Socket服务端和客户端

2.蓝牙通信消息接收端

设备连接后,跳转到通讯界面,首先我们要在通讯界面开启消息接收端服务,同样的我们要在一个线程中开启

得到bluetooth的inputstream输入流接收即可,同时我们可能接收到的是文件,需要将文件保存下来,记得申明相关权限。

消息接收端服务代码如下:

public  void  receiveMessage(){
      if (APP.bluetoothSocket == null){
          return;
      }
    try {
        InputStream inputStream = APP.bluetoothSocket.getInputStream();
        // 从客户端获取信息
        BufferedReader bff = new BufferedReader(new InputStreamReader(inputStream));
        String json;
        while (true) {
            while ((json = bff.readLine()) != null) {
                EventBus.getDefault().post(new MessageBean(RECEIVER_MESSAGE,json));
            }
            if ("file".equals(json)) {
                FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/test.gif");
                int length;
                int fileSzie = 0;
                byte[] b = new byte[1024];
                // 2、把socket输入流写到文件输出流中去
                while ((length = inputStream.read(b)) != -1) {
                    fos.write(b, 0, length);
                    fileSzie += length;
                    System.out.println("当前大小:" + fileSzie);
                    //这里通过先前传递过来的文件大小作为参照,因为该文件流不能自主停止,所以通过判断文件大小来跳出循环
                }
                fos.close();
                EventBus.getDefault().post(new MessageBean(RECEIVER_FILE,"文件保存成功"));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

3.蓝牙通信发送文本消息

通信和java中socket类似就不具体讲解了,需要注意的是当这里收到消息或者发送消息成功时,我这里用的是Eventbus异步通知

代码如下次:

/**
 * 发送文本消息
 *
 * @param message
 */
public static void sendMessage(String message) {
    if (APP.bluetoothSocket == null || TextUtils.isEmpty(message)) return;
    try {
        message += "\n";
        OutputStream outputStream = APP.bluetoothSocket.getOutputStream();
        outputStream.write(message.getBytes("utf-8"));
        outputStream.flush();
        EventBus.getDefault().post(new MessageBean(BltContant.SEND_TEXT_SUCCESS));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.蓝牙通信发送文件

/**
 * 发送文件
 */
public static void sendMessageByFile(String filePath) {
    if (APP.bluetoothSocket == null || TextUtils.isEmpty(filePath)) return;
    try {
        OutputStream outputStream = APP.bluetoothSocket.getOutputStream();
        //要传输的文件路径
        File file = new File(filePath);
        //说明不存在该文件
        if (!file.exists()){
            EventBus.getDefault().post(new MessageBean(BltContant.SEND_FILE_NOTEXIT));
            return;
        }
        //说明该文件是一个文件夹
        if (file.isDirectory()) {
            EventBus.getDefault().post(new MessageBean(BltContant.SEND_FILE_IS_FOLDER));
            return;
        }
        //1、发送文件信息实体类
        outputStream.write("file".getBytes("utf-8"));
        //将文件写入流
        FileInputStream fis = new FileInputStream(file);
        //每次上传1M的内容
        byte[] b = new byte[1024];
        int length;
        int fileSize = 0;//实时监测上传进度
        while ((length = fis.read(b)) != -1) {
            fileSize += length;
            Log.i("socketChat", "文件上传进度:" + (fileSize / file.length() * 100) + "%");
            //2、把文件写入socket输出流
            outputStream.write(b, 0, length);
        }
        //关闭文件流
        fis.close();
        //该方法无效
        //outputStream.write("\n".getBytes());
        outputStream.flush();
        EventBus.getDefault().post(new MessageBean(BltContant.SEND_FILE_SUCCESS));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

演示效果如下:

 

开源代码:https://github.com/huanglinqing123/Bluetooth

欢迎start和issue,如果没有github账号

可移步下载源码:

https://download.csdn.net/download/huangliniqng/10628117

欢迎关注技术公众号,微信号搜索ColorfulCode 代码男人

分享技术文章,投稿分享,不限技术种类,不限技术深度,让更多人因为分享而受益。

   

猜你喜欢

转载自blog.csdn.net/huangliniqng/article/details/82189735