Android蓝牙通讯(服务端、客户端)

Android蓝牙通讯

1. 在AndroidManifest.xml文件添加蓝牙操作权限

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2. 收发数据处理类

public class MyDataProcessThread extends Thread {

    private BluetoothSocket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    private static final int MAX_SIZE = 1024;

    private boolean isRunning = true;

    public MyDataProcessThread(BluetoothSocket socket) {
        this.socket = socket;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        byte[] buffer = new byte[MAX_SIZE];
        int readByte;
        while (isRunning) {
            try {
                readByte = inputStream.read(buffer);
                if (readByte != -1) {
                    byte[] out = new byte[readByte];
                    System.arraycopy(buffer, 0, out, 0, readByte);
                    //接收到的数据
                    byte[] reData = DataPackage.packB3(out);
                    write(reData);
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }

    /**
     * 发送数据到远程蓝牙
     * @param data 准备发送的数据
     * @return 发送是否成功
     * */
    public boolean write(byte[] data) {
        try {
            outputStream.write(data);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 关闭数据收发相关流对象
     * */
    public void cancel() {
        try {
            isRunning = false;
            this.interrupt();
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
            if (socket != null) {
                socket.close();
                socket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 服务端

public class MyBluetoothServer extends Thread {
    private BluetoothServerSocket serverSocket;
    private static final UUID UUID_ANDROID_DEVICE =
            UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private static final UUID UUID_OTHER_DEVICE =
            UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
    private static final String NAME_SECURE = "BluetoothChatSecure";
    private static final String NAME_INSECURE = "BluetoothChatInsecure";

    private boolean isSecure = true;
    private boolean isAndroidDevice = false;

    private List<MyDataProcessThread> threads;

    private boolean isRunning = true;

    public MyBluetoothServer() {
        Log.w(this.getClass().getName(), "create");
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothServerSocket temp = null;
        try {
            if (isAndroidDevice) {
                if (isSecure) {
                    temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_ANDROID_DEVICE);
                } else {
                    temp = adapter.listenUsingRfcommWithServiceRecord(NAME_INSECURE, UUID_ANDROID_DEVICE);
                }
            } else {
                if (isSecure) {
                    temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_OTHER_DEVICE);
                } else {
                    temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_OTHER_DEVICE);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        serverSocket = temp;
        threads = new ArrayList<>();
    }

    @Override
    public void run() {
        Log.w(getName(), "run");
        isRunning = true;
        while (isRunning) {
            try {
                BluetoothSocket socket = serverSocket.accept();
                Log.w(this.getClass().getName(), "accept");
                if (socket != null) {
                    MyDataProcessThread thread = new MyDataProcessThread(socket);
                    thread.start();
                    threads.add(thread);
                    Log.w(this.getClass().getName(), "threads size = " + threads.size());
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }

    public void cancel() {
        isRunning = false;
        this.interrupt();
        for (MyDataProcessThread thread : threads) {
            thread.cancel();

        }
        threads.clear();

        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.客户端

public class MyBluetoothClient extends Thread {
    private BluetoothSocket socket;
    private static final UUID UUID_ANDROID_DEVICE =
            UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private static final UUID UUID_OTHER_DEVICE =
            UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
    private final static int TIME_OUT = 10000;

    private boolean isSecure = true;
    private boolean isAndroidDevice = false;

    private MyDataProcessThread thread;

    public MyBluetoothClient(BluetoothDevice device) {
        BluetoothSocket temp = null;
        try {
            if (isSecure) {
                if (isAndroidDevice) {
                    temp = device.createRfcommSocketToServiceRecord(UUID_ANDROID_DEVICE);
                } else {
                    temp = device.createRfcommSocketToServiceRecord(UUID_OTHER_DEVICE);
                }
            } else {
                if (isAndroidDevice) {
                    temp = device.createInsecureRfcommSocketToServiceRecord(UUID_ANDROID_DEVICE);
                } else {
                    temp = device.createInsecureRfcommSocketToServiceRecord(UUID_OTHER_DEVICE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        socket = temp;
    }

    @Override
    public void run() {
        if (socket == null) {
            return;
        }
        try {
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            cancel();
        }
        thread = new MyDataProcessThread(socket);
        thread.start();
    }

    /**
     * 发送数据
     * @param data 字节数据
     * @return 发送结果,true - 发送成功; false - 发送失败
     * */
    public boolean write(byte[] data) {
        return thread.write(data);
    }

    /**
     * 关闭相关流对象
     * */
    public void cancel() {
        try {
            if (thread != null) {
                thread.cancel();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.Activity相关调用

1). 获取已配对蓝牙设备

private BluetoothDevice device;
private void showBondedDevice() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            return;
        }
        if (!adapter.isEnabled()) {
            //打开系统蓝牙设置
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
            return;
        }

        Set<BluetoothDevice> devices = adapter.getBondedDevices();
        if (devices.size() > 0) {
            for (BluetoothDevice item : devices) {
                Log.i("BondedDevices", "device : " + item.getName());
            }
        }
    }

2). 服务端调用

    private void startServer() {
        MyBluetoothServer server = new MyBluetoothServer();
        server.start();
    }

3). 客户端调用

	private MyBluetoothClient client;
	
    /**
     * 连接某个已配对蓝牙设备
     * */
    private void startClient() {
        client = new MyBluetoothClient(device);
        client.start();
    }
    /**
     * 在子线程中发送数据
     * @param data 要发送的数据
     * */
    private void write(final byte[] data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.write(data);
            }
        }).start();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值