在AndroidManifest.xml文件中添加蓝牙权限:
开启蓝牙模块: BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
扫描附近的蓝牙设备: bluetoothAdapter.startDiscovery(); BroadcastReceiver receiver = 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); // 进行一些设备的处理操作 } } }; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter);
连接指定的蓝牙设备: BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect();
在连接成功后,在两个设备之间传输数据: OutputStream outputStream = socket.getOutputStream(); outputStream.write(buffer); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int count = inputStream.read(buffer); String result = new String(buffer, 0, count);