蓝牙代码整理

本文详细介绍通过Android系统实现蓝牙连接的过程,包括蓝牙适配器的获取、蓝牙设备的搜索与连接、数据发送等关键步骤,并提供完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

step1:获取蓝牙适配器

private BluetoothAdapter mBtAdapter;            mBtAdapter=BluetoothAdapter.getDefaultAdapter();

step2:强制开启蓝牙设备

if(!mBtAdapter.isEnabled()){  
    mBtAdapter.enable();  
}

step3:获取搜索/已连接的Device

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
或已经连接
private Set<BluetoothDevice>pairedDevices = mBtAdapter.getBondedDevices();

然后从该设备获取地址
mBtAddress = device.getAddress();

step5:根据搜索到的蓝牙设备的MAC地址,得到该设备

mBtDevice = mBtAdapter.getRemoteDevice(mBtAddress);

step6:开启客户端线程,线程里面完成了与SPP协议的连接

mBtClientConnectThread = new clientThread();  
             mBtClientConnectThread.start();
连接过程:(必须放在try中进行)
    try {  
//取消搜索设备的动作,否则接下来的设备连接会失败  
            mBtAdapter.cancelDiscovery();  
//根据device获取socket  
            mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
//连接socket  
            mBtSocket.connect();  
        } catch (IOException e) {  
            e.printStackTrace();  
            Log.e("connect", "", e);  
            Log.d("clientThread", "连接失败");  

        }

step7: 发送数据

try {  
        OutputStream mOutputStream = mBtSocket.getOutputStream();   
        mOutputStream.write(msg.getBytes()); //发送出去的值为:msg  
        mOutputStream.flush();
    } catch (IOException e) {  
            e.printStackTrace();  
        }

step8: 清场

if(mBtClientConnectThread!=null)  
                {  
                    mBtClientConnectThread.interrupt();  
                    mBtClientConnectThread= null;  
                }  
                if (mBtSocket != null) {  
                    try {  
                        mBtSocket.close();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    mBtSocket = null;  
                }  
            };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值