Android蓝牙操作

1.添加蓝牙权限

 <uses-permission android:name = "android.permission.BLUETOOTH"/>
    <!--启用应用启动设备发现或者操作蓝牙设备的超级管理员-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 

2.获取蓝牙设备

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
                    Toast.makeText(MainActivity.this, "未找到设备", Toast.LENGTH_LONG).show();
                    return;
                }

if (!bluetoothAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                }

 

3.搜索设备

Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (final BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                final Button btnDevice = findViewById(R.id.device_btn);
                btnDevice.setText(device.getAddress());
                btnDevice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {try {
                            new ConnectThread(device).run();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }

 

4.连接设备

private class ConnectThread extends Thread {
        private BluetoothDevice mDevice;
        private BluetoothSocket mSocket;

        public ConnectThread(BluetoothDevice device) throws IOException {
            mDevice = device;
            mSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.randomUUID());
            Log.d("aaa", "start");
        }

        public void run() {
            // 关闭发现设备
            bluetoothAdapter.cancelDiscovery();
            try {
                mSocket.connect();
            } catch (IOException connectException) {
                try {
                    mSocket.close();
                } catch (IOException closeException) {
                    return;
                }
            }
            Log.d("aaa", "connected");
            // 自定义方法
            manageConnectedSocket(mSocket);
        }

        private void manageConnectedSocket(BluetoothSocket socket) {
            //读取数据
        }

        public void cancle() {
            try {
                mSocket.close();
            } catch (IOException closeException) {

            }
        }
    }

 

Android蓝牙操作

上一篇:(一)appium环境安装相关的流程和原理(老版)


下一篇:2020/12/25