Android设备可以通过蓝牙和其他设备进行通信,包括其他Android设备和外部设备,如蓝牙耳机、打印机和传感器等。在本指南中,我们将详细介绍如何使用Android蓝牙API建立和管理蓝牙连接。
一、检查设备是否支持蓝牙
首先,我们需要检查当前设备是否支持蓝牙功能。
private boolean isBluetoothSupported() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return bluetoothAdapter != null;
}
使用上述代码可以检查设备是否支持蓝牙功能。如果返回true,则设备支持蓝牙功能。
二、开启蓝牙
在使用蓝牙功能之前,需要确保蓝牙已经开启。
private boolean isBluetoothEnabled() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
}
private void enableBluetooth(Activity activity) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "无法打开蓝牙", Toast.LENGTH_SHORT).show();
}
}
}
使用上述代码可以检查蓝牙是否已开启。如果返回true,则蓝牙已经开启。如果返回false,则需要启动启用蓝牙对话框以请求开启蓝牙。
三、搜索设备
在与其他设备进行通信之前,需要搜索周围的设备。在搜索设备之前,需要确保蓝牙已经开启。
private void startDiscovery() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
Toast.makeText(this, "搜索设备中...", Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "发现设备:" + device.getName() + " - " + device.getAddress());
}
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(discoveryReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(discoveryReceiver);
}
使用上述代码可以开始搜索设备。当找到设备时,会收到广播,并且在日志中打印设备名称和地址。如果找不到设备,可以尝试重新启动搜索或检查设备是否打开蓝牙。
四、连接设备
当找到要连接的设备时,需要建立连接。建立连接前,需要确保蓝牙已经开启。
private void connect(String address) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Log.d(TAG, "连接成功:" + device.getName());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用上述代码可以连接指定地址的设备。如果连接成功,则会在日志中打印设备名称。如果连接失败,则会抛出IOException。
五、数据传输
连接建立后,可以开始在设备之间传输数据。以下代码演示如何发送和接收文本数据。
private void send(String message) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
return;
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
BluetoothSocket socket = null;
OutputStream outputStream = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
Log.d(TAG, "消息发送成功:" + message);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private final BroadcastReceiver receiveReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Log.d(TAG, "连接成功");
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.d(TAG, "连接断开");
} else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
Log.d(TAG, "断开请求");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
}
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiveReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiveReceiver);
}
使用上述代码可以在设备之间传输文本数据。发送消息时,使用OutputStream将文本字符串转换为字节,并通过BluetoothSocket发送。在接收消息时,使用BroadcastReceiver监听连接的状态,并根据状态更新UI或执行其他操作。
六、总结
本指南中介绍了如何使用Android蓝牙API建立和管理蓝牙连接。需要注意的是,在使用蓝牙功能之前,需要确保蓝牙已经开启,并且在连接设备之前,需要确保已经搜索到要连接的设备。为了传输数据,可以使用OutputStream将文本转换为字节并发送。在接收数据时,可以使用BroadcastReceiver监听连接状态并执行操作。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/186240.html
微信扫一扫
支付宝扫一扫