【Android -- 蓝牙】蓝牙通信

一、简介

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

在这里插入图片描述

二、蓝牙通信消息接收端

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

得到 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();
    }
 
}

三、蓝牙通信发送文本消息

需要注意的是当这里收到消息或者发送消息成功时,我这里用的是 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();
    }
}

四、蓝牙通信发送文件

/**
 * 发送文件
 */
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();
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kevin-Dev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值