Android 蓝牙聊天简单Demo

Android 蓝牙聊天简单Demo

蓝牙技术是一种近距离通信技术,自从研发至今,已经被广泛应用,生活中处处可见蓝牙耳机,有些穿戴设备也是基于蓝牙进行通信的,蓝牙通信功耗小,对于近距离通信是一个不错的选择。这篇博客就是基于Android蓝牙实现的一个建议聊天Demo。

基本步骤和要求

基本步骤

  1. 客户端和服务端都打开蓝牙并是可被搜索到的状态
  2. 将客户端和服务端进行配对
  3. 配对成功之后就客户端可以通过 BluetoothSocket 对象的 connect() 方法进行连接,服务端通过 BluetoothServerSocket 对象的 accept()方法监听客服端的链接
  4. 连接成功之后就可以通过 BluetoothSocket 对象拿到 OutputStreamInputStream输入输出流对象了
  5. 拿到输入输出流对象,就可以进行读写操作

要求

  1. 需要2台手机,一台作为客户端,另外一台作为服务端
  2. 2台手机都要装上应用,并打开蓝牙建立连接

代码下载和效果展示

GitHub下载和效果查看

相关API说明

获取蓝牙适配器对象

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

判断蓝牙是否打开了和打开蓝牙

 if (!mBluetoothAdapter.isEnabled()) { // 判断蓝牙是否打开了
        boolean enable = mBluetoothAdapter.enable();
        if(enable)
            Toast.makeText(mContext, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(mContext, "蓝牙打开失败", Toast.LENGTH_SHORT).show();

        // 系统界面打开蓝牙
        //Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        //mContext.startActivity(intent);
    }else{
        Toast.makeText(mContext, "蓝牙已打开", Toast.LENGTH_SHORT).show();
    }

开始搜索蓝牙设备和取消搜索

mBluetoothAdapter.startDiscovery();  // 开始搜索
mBluetoothAdapter.cancelDiscovery(); // 取消搜索

注册搜索到蓝牙设备广播

mBluetoothReceiver = new BluetoothReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mContext.registerReceiver(mBluetoothReceiver, intentFilter);

// 搜索到蓝牙广播
class BluetoothReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND == action) { // 找到设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            Message message = Message.obtain();
            message.what = MSG_WHAT_FOUND_DEVICE;
            message.obj = device;
            mHandler.sendMessage(message);
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) { // 搜索完成
            mHandler.sendEmptyMessage(MSG_WHAT_FINISHED_SEARCH);
        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == action) { // 配对状态改变
            int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
            switch (state) {
                case BluetoothDevice.BOND_NONE:
                    mHandler.sendEmptyMessage(MSG_WHAT_BOND_NONE);
                    LogUtil.d("BOND_NONE 删除配对");
                    break;
                case BluetoothDevice.BOND_BONDING:
                    mHandler.sendEmptyMessage(MSG_WHAT_BOND_BONDING);
                    LogUtil.d("BOND_BONDING 正在配对");
                    break;
                case BluetoothDevice.BOND_BONDED:
                    mHandler.sendEmptyMessage(MSG_WHAT_BOND_BONDED);
                    LogUtil.d("BOND_BONDED 配对成功");
                    break;
            }
        }
    }
}

配对

BluetoothDevice 对象的 createBond() 方法

客户端建立链接

// 蓝牙 Socket 对象
private BluetoothSocket mBluetoothSocket;
if (secure) {
    mBluetoothSocket =
            mBluetoothDevice.createRfcommSocketToServiceRecord(Constants.MY_UUID_SECURE);
} else {
    mBluetoothSocket =
            mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(Constants.MY_UUID_INSECURE);
}
if (!mBluetoothSocket.isConnected())
    mBluetoothSocket.connect();

服务端监听链接

if (secure) {
    mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
            Constants.NAME_SECURE, Constants.MY_UUID_SECURE);
} else {
    mBluetoothServerSocket = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(
            Constants.NAME_INSECURE, Constants.MY_UUID_INSECURE);
}
// 等待链接
BluetoothSocket bluetoothSocket = mBluetoothServerSocket.accept();
// 判断是否建立链接成功
bluetoothSocket.isConnected()

建立链接成功之后,不管是客户端还是服务端都返回了一个 BluetoothSocket 对象,通过 BluetoothSocket对象就可以获取到输入输出流了

OutputStream outputStream = bluetoothSocket.getOutputStream();
InputStream inputStream = bluetoothSocket.getInputStream();

最后,就是简单的I/O读写操作了

以上展示出来的只是部分相关的API,具体的实现过程代码比较多,就不在这里全部贴出来的,如果有需要的话可以到GitHub上下载。

你可能感兴趣的:(Android,知识)