AndroidManifest.xml
<!--蓝牙权限--><uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /><uses-permission android:name="android.permission.BLUETOOTH_SCAN" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
注册广播接收者监听蓝牙状态:
try {if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1);}//获取 BluetoothHeadset 代理// bluetoothAdapter.getProfileProxy(getApplicationContext(), serviceListener, BluetoothProfile.HEADSET);isSupportBluetooth();isBtConDeviceByMac();IntentFilter filter = new IntentFilter();filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);filter.addAction(BluetoothDevice.ACTION_FOUND);filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //绑定状态监听filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);registerReceiver(bluetoothReceiver, filter);} catch (Exception e) {e.printStackTrace();}
连接那一块儿的代码好像不能用。
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();private static final String tagBlt = "BluetoothA";public void isSupportBluetooth() {if (bluetoothAdapter == null) {Log.d(tagBlt, "设备不支持蓝牙");}if (!bluetoothAdapter.isEnabled()) {Log.d(tagBlt, "蓝牙未启用");} else {Log.d(tagBlt, "蓝牙已经启用");}}BluetoothDevice deviceConnect;//经典蓝牙连接状态public void isBtConDeviceByMac() {//String strCurBtMacString deviceName = "";String deviceAddress = "";try {Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);method.setAccessible(true);int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);if (state == BluetoothAdapter.STATE_CONNECTED) {Log.d(tagBlt, "BluetoothAdapter.STATE_CONNECTED已经连接");if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();Log.d(tagBlt, "已经配对的设备数量" + devices.size());for (BluetoothDevice device : devices) {Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);method.setAccessible(true);boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);if (isConnected) {deviceConnect = device;deviceName = device.getName();deviceAddress = device.getAddress();Log.d(tagBlt, "已经连接的设备名称:connected:" + deviceName + ", 地址:" + deviceAddress);// 保存设备信息以便后续使用saveConnectedDeviceInfo(deviceName, deviceAddress);}}}if (state == BluetoothAdapter.STATE_DISCONNECTED) {Log.d(tagBlt, "连接状态" + state);Log.d(tagBlt, "你好");// connectToDevice(deviceConnect);}// Log.d("Bluetooth", "连接状态"+state);} catch (Exception e) {e.printStackTrace();}}public void connectToDevice(BluetoothDevice device) {BluetoothSocket bluetoothSocket = null;try {// 使用设备的 UUID 创建 BluetoothSocketUUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 通用串口服务的 UUIDif (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);// 连接到设备bluetoothSocket.connect();Log.d(tagBlt, "连接成功: " + device.getName());// 这里可以进行数据传输} catch (IOException e) {Log.e(tagBlt, "连接失败: " + e.getMessage());try {if (bluetoothSocket != null) {bluetoothSocket.close();}} catch (IOException closeException) {Log.e(tagBlt, "关闭连接失败: " + closeException.getMessage());}}}private HashMap<String, String> connectedDevices = new HashMap<>();private void saveConnectedDeviceInfo(String name, String address) {connectedDevices.put(name, address);}/* Handler handler=new Handler();Runnable bltConnectRunnable= new Runnable() {@Overridepublic void run() {connectToDevice(deviceConnect);Log.d(tagBlt,"正在执行连接");handler.postDelayed(this,5000);}};handler.post(bltConnectRunnable);*/private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {final String action = intent.getAction();// BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (BluetoothDevice.ACTION_FOUND.equals(action)) {Log.d(tagBlt, "蓝牙设备已发现");} else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {// 蓝牙设备已连接Log.d(tagBlt, "蓝牙设备已连接");} else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {Log.d(tagBlt, "蓝牙设备正准备断开连接");} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {// 蓝牙设备已断开Log.d(tagBlt, "蓝牙设备已断开可以执行一些操作了");Log.d(tagBlt, "可以执行一些操作了");// 触发重连逻辑if(deviceConnect!=null){connectToDevice1(deviceConnect);Log.d(tagBlt, "deviceConnect不为null,已经调用connectToDevice1方法了");}else{Log.d(tagBlt, "deviceConnect为null,并没有调用connectToDevice1");}}if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);switch (state) {case BluetoothAdapter.STATE_OFF:Log.d(tagBlt, "蓝牙已关闭22");break;case BluetoothAdapter.STATE_ON:Log.d(tagBlt, "蓝牙已开启22");break;case BluetoothAdapter.STATE_TURNING_OFF:Log.d(tagBlt, "蓝牙正在关闭22");break;case BluetoothAdapter.STATE_TURNING_ON://Toast.makeText(context, "蓝牙正在开启22", Toast.LENGTH_SHORT).show();Log.d(tagBlt, "蓝牙正在开启22");break;}}}};private BluetoothGatt bluetoothGatt;public void connectToDevice1(BluetoothDevice device) {if (bluetoothGatt != null) {if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}bluetoothGatt.disconnect();bluetoothGatt.close();Log.d(tagBlt, "bluetoothGatt != null");}if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}bluetoothGatt = device.connectGatt(this, false, gattCallback);Log.d(tagBlt, "bluetoothGatt = device.connectGatt(this, false, gattCallback);");}private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {if (newState == BluetoothGatt.STATE_CONNECTED) {// 连接成功if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}gatt.discoverServices(); // 发现服务Log.d(tagBlt, "discoverServices");} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {// 连接断开// 可以在这里实现重连逻辑Log.d(tagBlt, "---BluetoothGatt.SSTATE_DISCONNECTED");}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {Log.d(tagBlt, " BluetoothGatt.GATT_SUCCESS");}}// 其他回调方法可以根据需要实现};public void disconnect() {if (bluetoothGatt != null) {if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling// ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding// public void onRequestPermissionsResult(int requestCode, String[] permissions,// int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}bluetoothGatt.disconnect();bluetoothGatt.close();bluetoothGatt = null;}}