您当前的位置: 首页 >  android

Kevin-Dev

暂无认证

  • 0浏览

    0关注

    544博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Android -- 蓝牙】蓝牙通信

Kevin-Dev 发布时间:2019-01-07 23:09:47 ,浏览量:0

一、简介

无论是做 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();
    }
}
关注
打赏
1658837700
查看更多评论
立即登录/注册

微信扫码登录

0.0440s