蓝牙讲解下--通信

名称解释

  • UUID 含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织应用在分布式计算环境 (Distributed Computing Environment, DCE) 领域的一部分
  • Rfcomm 一个基于欧洲电信标准协会ETSI07.10规程的串行线性仿真协议。

整体思路

蓝牙讲解下--通信_第1张图片

创建服务端线程

public class ServerThread extends Thread {
    private static final String TAG = "Chat";
    private static final String NAME = "Chat";
    String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    // 通过一个规定好的串号,生成一个UUID号
    UUID MY_UUID = UUID.fromString(SPP_UUID);
    /**
     * 服务端的socket
     */
    private BluetoothServerSocket serverSocket;

    private BufferedReader bufferedReader;
    private BufferedWriter bufferedWriter;
    private Handler handler;

    /**
     * 服务端线程
     * 
     * @param handler
     *            handler对象,用于发送消息给主线程
     * @param bluetoothAdapter
     */
    public ServerThread(Handler handler, BluetoothAdapter bluetoothAdapter) {
        try {
            this.handler = handler;
            // 通过BluetoothAdapter创建一个服务端,NAME是自己定义 UUID需要根据一个串号去生成
            serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(
                    NAME, MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        while (true) {
            try {
                // 阻塞
                BluetoothSocket socket = serverSocket.accept();
                // 如果接受到这样一个客户端,就获取输入输出流
                bufferedReader = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(
                        socket.getOutputStream()));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    Log.i(TAG, "收到客户端的消息" + line);
                    // 收到消息,发送给主线程,显示界面上 tv_content
                    handler.obtainMessage(MyChatActivity.ACCEPT_MESSAGE, line)
                            .sendToTarget();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 服务端发送消息给客户端
     * 
     * @param msg
     */
    public void sendMessage(String msg) {
        if (bufferedWriter != null) {
            try {
                //发送消息,并进行刷新
                bufferedWriter.write(msg + "\n");
                bufferedWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "服务端没有获取到任何的客户端");
            handler.obtainMessage(MyChatActivity.FAILED, "服务端没有获取到任何的客户端")
                    .sendToTarget();
        }
    }
}

创建客户端线程

package com.example.bluetooth_8g.chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.UUID;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class ClientThread extends Thread {
    private BluetoothDevice bluetoothDevice;
    private Handler handler;
    private static final String TAG = "Chat";
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    // 通过一个规定好的串号,生成一个UUID号
    private static final UUID MY_UUID = UUID.fromString(SPP_UUID);
    private BufferedReader bufferedReader;
    private BufferedWriter bufferedWriter;
    /**
     * 设定一个标记值,来标记客户端连接是否成功
     */
    public static boolean flag = false;

    /**
     * 在创建这个客户端的线程的时候,需要将要连接的bluetoothDevice传递过来
     * 
     * @param bluetoothDevice
     * @param handler
     */
    public ClientThread(BluetoothDevice bluetoothDevice, Handler handler) {
        this.handler = handler;
        this.bluetoothDevice = bluetoothDevice;
    }

    @Override
    public void run() {
        super.run();
        try {
            // 获取客户端的socket
            BluetoothSocket socket = bluetoothDevice
                    .createRfcommSocketToServiceRecord(MY_UUID);
            // 连接服务器------要么成功,要么异常
            socket.connect();
            // 如果没有抛出异常,代表连接成功,进行一个标志位
            flag = true;
            // 将字节流转换成字符流
            bufferedReader = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                Log.i(TAG, "收到服务端的消息" + line);
                // 收到消息,发送给主线程,显示界面上 tv_content
                handler.obtainMessage(MyChatActivity.ACCEPT_MESSAGE, line)
                        .sendToTarget();
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 如果抛出异常,进行一下标志位的置位
            flag = false;
            Log.i(TAG, "客户端连接失败");
        }
    }

    /**
     * 客户端线程发送消息给服务端
     * 
     * @param msg
     */
    public void sendMessage(String msg) {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.write(msg + "\n");
                Log.i(TAG, "客户端发送消息:" + msg);
                bufferedWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "客户端未连接");
            handler.obtainMessage(MyChatActivity.FAILED, "客户端未连接")
                    .sendToTarget();
        }
    }
}

收发数据

  • 开启服务端的线程

    “`bash
    // 获取defaultAdapter
    defaultAdapter = BluetoothAdapter.getDefaultAdapter();
    // 创建服务端
    serverThread = new ServerThread(handler, defaultAdapter);
    // 开启服务端线程,等待接收客户端
    serverThread.start();

* 开始客户端的线程
```bash
        // 创建客户端线程
        // 获取要连接到蓝牙设备
        remoteDevice = defaultAdapter.getRemoteDevice(address);
        clientThread = new ClientThread(remoteDevice, handler);
        clientThread.start();




<div class="se-preview-section-delimiter"></div>
  • 发送数据
String msg = et_content.getText().toString().trim();
        if (ClientThread.flag) {
            // 作为客户端存在
            clientThread.sendMessage(msg);
        } else {
            serverThread.sendMessage(msg);
        }
* 发送数据
```bash
String msg = et_content.getText().toString().trim();
        if (ClientThread.flag) {
            // 作为客户端存在
            clientThread.sendMessage(msg);
        } else {
            serverThread.sendMessage(msg);
        }

代码见

http://download.csdn.net/detail/zhiyuan0932/9498223
相关文章 http://blog.csdn.net/zhiyuan0932/article/details/51210948

你可能感兴趣的:(通信,蓝牙)