Socket蓝牙

本文介绍了如何在Android中操作蓝牙,包括初始化蓝牙功能、打开/关闭蓝牙、获取已配对设备、启动设备发现、设置设备为可发现状态、监听蓝牙状态变化、连接已配对和未配对设备,以及蓝牙通信的基本步骤。

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

使用蓝牙需要的权限: 
//允许程序连接到已配对的蓝牙设备
<uses-permission android:name="android.permission.BLUETOOTH"/>


//允许程序发现和配对蓝牙设备   
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>


蓝牙模块的串口(规定好的)
 String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";

//蓝牙开关

// 初始化本机蓝牙功能
BluetoothAdapter  btAdapter = BluetoothAdapter.getDefaultAdapter();
//打开蓝牙
btAdapt.enable();
//关闭蓝牙
btAdapt.disable();

//已经配对的蓝牙

btAdapt.getState()//得到当前设备的蓝牙状态


//先判断当前蓝牙设备是否是打开状态
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
Toast.makeText(MainActivity.this, "请先打开蓝牙", 1).show();
return;
}
// 获得以经匹配过得蓝牙设备,是一个数组
Object[] lstDevice = btAdapt.getBondedDevices().toArray();
//循环取出每一个设备的对象
for (int i = 0; i < lstDevice.length; i++) {


BluetoothDevice device = (BluetoothDevice) lstDevice[i];
      //将设备信息取出,展示在listView上


String str = "已配对设备   |   " + device.getName() + "|"
+ device.getAddress(); // 获取设备名称和mac地址


listDevices.add(str);
        adtDevices.notifyDataSetChanged();
btAdapt.startDiscovery();// 启动蓝牙;发现设备}



//  本机可以被其他设备搜索

Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);// 设备可以被发现


discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);// 设备可见时间,最大可设置3600


startActivity(discoverableIntent);

//获取蓝牙设备的连接信息


Android手机上的蓝牙,在蓝牙模块状态发生变化时,是以发广播的形式,通知要使用蓝牙模块的应用,所以要用到广播接收者


BluetoothDevice.ACTION_FOUND;// 发现蓝牙设备的广播
BluetoothDevice.ACTION_BOND_STATE_CHANGED;// 蓝牙设备连接状态改变的广播


String action = intent.getAction();//获得广播接收者的动作
BluetoothDevice device = null;
//通过广播携带的动作去匹配是不是发现了蓝牙设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {


device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//得到搜索到的蓝牙设备对象
//如果发现的设备,之前没有与本机蓝牙进行配对过
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
//通过listView展示未配对蓝牙信息
String str = "未配对设备|   " + device.getAddress() + "  |  "+ device.getName();
if (listDevices.indexOf(str) == -1) { listDevices.add(str); adtDevices.notifyDataSetChanged();}}}

//获取蓝牙设备的连接信息

/通过设备连接状态改变的广播,判断当前设备的状态
if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){


device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


switch (device.getBondState()) {
case BluetoothDevice.BOND_BONDING:


Log.d("BlueToothTestActivity", "正在配对......"); break;


case BluetoothDevice.BOND_BONDED:


Log.d("BlueToothTestActivity", "完成配对");
connect(device);//连接设备 break;


case BluetoothDevice.BOND_NONE:


Log.d("BlueToothTestActivity", "取消配对");break;
}
}

//连接设备(已经配对的设备)

//设置UUID;UUID是128位的不可变表示全局惟一标识符
//UUID is an immutable representation of a 128-bit universally unique identifier (UUID).

UUID uuid = UUID.fromString(SPP_UUID);
try {
btSocket =                                                                    btDev.createRfcommSocketToServiceRecord(uuid);


Log.d("BlueToothTestActivity", "开始连接...");


btSocket.connect();


} catch (IOException e) {

e.printStackTrace();


}


//连接设备(没有配对的设备)

if(btAdapt.isDiscovering()) {//判断蓝牙是否处于搜索状态
btAdapt.cancelDiscovery()//是搜索状态时,取消搜索
};


String str = lstDevices.get(arg2);//获得保存在集合内的蓝牙设备信息


String[] values = str.split("\\|");       String address = values[2];


//得到远程蓝牙设备
BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
//判断该设备是否已经进行过配对
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//利用反射方法调用createBond
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");


Log.d("BlueToothTestActivity", "开始配对");
//
returnValue = (Boolean) createBondMethod.invoke(btDev);
}

//蓝牙通信(客户端)

UUID uuid = UUID.fromString(SPP_UUID);//解析一个字符串格式的UUID


//指定蓝牙地址,得到远程蓝牙设备,目的是得到一个蓝牙的套接字
BluetoothDevice remoteDevice = bluetoothAdapter .getRemoteDevice("34:4D:F7:E8:CB:06");


//根据UUID创建并返回一个BluetoothSocket 
BluetoothSocket socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
//连接
socket.connect();

//蓝牙通信(服务器端)

UUID uuid = UUID.fromString(SPP_UUID);//解析一个字符串格式的UUID


//创建一个BluetoothSocket实例
BluetoothServerSocket serviceSocket = bluetoothAdapter .listenUsingRfcommWithServiceRecord("test", uuid);
//得到一个蓝牙的套接字
BluetoothSocket socket = serviceSocket.accept();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值