Android开发——蓝牙与外部设备连接

一、获取蓝牙权限

在Manifest.xml文件中添加蓝牙权限声明



    
    
    
    
    
    
    
    
    

    
        
        
            
                

                
            
        
    

二、检查设备是否支持蓝牙

BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter == null) {
    Toast.makeText(MainActivity.this, "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();
}

三、申请蓝牙权限

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.
    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.BLUETOOTH_CONNECT},REQUEST_BLUETOOTH_PERMISSION);
}

四、寻找目标设备

Set bondedDevices = defaultAdapter.getBondedDevices();
BluetoothDevice targetDevice = null;
if (bondedDevices.size() > 0) {
    for (BluetoothDevice device:bondedDevices){
        if (device.getName().equals("目标设备名称")){
            targetDevice=device;
            break;
        }
    }
}

五、数据传输

BluetoothSocket bluetoothSocket = null;
InputStream inputStream = null;
byte[] buffer = new byte[1024];
int bytes;
try {
    bluetoothSocket = targetDevice.createRfcommSocketToServiceRecord(UUID.fromString("这个 UUID 需要与外部设备的蓝牙协议一致"));
    bluetoothSocket.connect();
    inputStream = bluetoothSocket.getInputStream();
} catch (IOException e) {
    throw new RuntimeException(e);
}
while(true){
    try {
        bytes = inputStream.read(buffer);
        String data = new String(buffer,0,bytes);
        //处理数据
    } catch (IOException e) {
        break;
    }
}
try {
    bluetoothSocket.close();
} catch (IOException e) {
    throw new RuntimeException(e);
}

你可能感兴趣的:(android)