第一步
//获取系统蓝牙适配器管理类
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
private void initBluetooth() {
// 询问打开蓝牙
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
}
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
} else {
mBluetoothAdapter.startDiscovery();
}
// 注册用以接收到已搜索到的蓝牙设备的receiver
IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBluetoothReceiver, mFilter);
// 注册搜索完时的receiver
mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBluetoothReceiver, mFilter);
}
第二步
// 广播接收发现蓝牙设备
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//发现蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//根据你的设备address或者name来判断是否是你指定的设备
if (device.getAddress() != null && deviceName.contains(device.getAddress())) {
tagDevice = device;
//开启新线程进行连接
new ClientThread(tagDevice).start();
mBluetoothAdapter.cancelDiscovery();
return;
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//蓝牙搜索完成
// 蓝牙搜索是非常消耗系统资源开销的过程,搜索完毕后应该及时取消搜索
mBluetoothAdapter.cancelDiscovery();
}
}
};
第三步
/**
* 蓝牙连接的线程
*/
private class ClientThread extends Thread {
private BluetoothDevice device;
public ClientThread(BluetoothDevice device) {
this.device = device;
}
@Override
public void run() {
try {
socket = device.createRfcommSocketToServiceRecord(UUID.fromString(BLUETOOTH_UUID));
Log.d("Bluetooth", "连接服务端...");
if (socket != null && !socket.isConnected()) {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
Log.d("Bluetooth", "连接建立.");
//连接成功后开启读取该蓝牙设备数据的线程
new ReadThread(socket).start();
}
} catch (Exception e) {
//socket连接失败
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
} catch (Exception e1) {
Log.e("Bluetooth", e1.toString());
try {
socket.close();
} catch (IOException ie) {
}
}
return;
}
}
}
//连接设备和读取数据都需要新启线程在子线程中进行,因为过程比较耗时,如果不在子线程影响效率和阻塞UI。
//读写线程
private class ReadThread extends Thread {
private BluetoothSocket socket;
public ReadThread(BluetoothSocket socket) {
this.socket = socket;
}
@Override
public void run() {
byte[] buffer = new byte[1024];
InputStream mmInStream = null; //建立输入流读取数据
try {
mmInStream = socket.getInputStream();
int num = mmInStream.read(buffer);
while (num != -1 && isStop) {
num = mmInStream.read(buffer);
String str = new String(buffer);
String[] split = str.split("=");
StringBuffer stringBuffer = new StringBuffer(split[5]);
//获取流数据根据编码规则得到想要的数据
String s = stringBuffer.reverse().toString();
Log.e("Bluetooth", s);
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (mmInStream != null) {
try {
mmInStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
各种UUID链接:https://blog.csdn.net/weixin_40108380/article/details/105671120