Android13下能否绕过蓝牙配对窗口,通过设备地址自动传输文件?
蓝牙文件直连发送:跳过手动选设备无效的解决办法
问题背景
现有可正常接收蓝牙文件的Java代码,希望跳过手动选择蓝牙设备步骤,不使用Socket,通过intent.putExtra传入设备地址实现直连发送,但尝试的代码无效果。
原尝试代码:
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType("*/*"); sendIntent.setPackage("com.android.bluetooth"); File privateFile = new File(privateFileName); Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", privateFile); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); this.grantUriPermission("com.android.bluetooth", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(sendIntent);
额外添加的无效代码:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(device_address); sendIntent.putExtra( "android.bluetooth.device.extra.DEVICE", device);
可行解决方案
1. 改用ACTION_SEND_TO并传入设备Uri
系统蓝牙应用的ACTION_SEND不支持直接指定目标设备,需替换为ACTION_SEND_TO,通过蓝牙设备的Uri锁定目标:
// 获取目标蓝牙设备 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice targetDevice = bluetoothAdapter.getRemoteDevice(device_address); // 构建蓝牙设备的Uri格式:bt://[设备MAC地址] Uri deviceUri = Uri.parse("bt://" + targetDevice.getAddress()); // 创建发送Intent Intent sendIntent = new Intent(Intent.ACTION_SEND_TO); sendIntent.setType("*/*"); sendIntent.setPackage("com.android.bluetooth"); sendIntent.setData(deviceUri); // 配置要发送的文件 File privateFile = new File(privateFileName); Uri fileUri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", privateFile); sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri); // 授予蓝牙应用访问文件的权限 grantUriPermission("com.android.bluetooth", fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); startActivity(sendIntent);
2. 检查权限与配对状态
- 权限要求:Android 11及以下需申请
BLUETOOTH、BLUETOOTH_ADMIN权限;Android 12+需额外申请BLUETOOTH_CONNECT权限,且需动态申请这些危险权限。 - 设备配对:目标蓝牙设备必须已与当前设备完成配对,未配对设备无法直接发送,需先触发配对流程。
3. 移除包名尝试隐式调用
如果指定com.android.bluetooth包名仍无效,可尝试去掉包名,让系统自动匹配蓝牙处理应用:
Intent sendIntent = new Intent(Intent.ACTION_SEND_TO); sendIntent.setType("*/*"); sendIntent.setData(deviceUri); sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri); grantUriPermission("com.android.bluetooth", fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); startActivity(sendIntent);
内容的提问来源于stack exchange,提问作者e s
相关产品推荐
相关产品推荐

