我们正在尝试使用CompanionDeviceManager类将我们的BLE设备与Android(版本10)手机配对,而无需获取位置权限。
为了测试目的,我们在测试设备周围激活了多部手机和BLE设备的蓝牙。
我们使用了来自官方网站的示例代码,但没有成功。
将以下代码添加到AndroidManifest文件中:
<uses-feature android:name="android.hardware.bluetooth"/>
<uses-feature android:name="android.software.companion_device_setup"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
MainActivity的完整代码:
public class MainActivity extends AppCompatActivity {
private CompanionDeviceManager deviceManager;
private AssociationRequest pairingRequest;
private BluetoothDeviceFilter deviceFilter;
private static final int SELECT_DEVICE_REQUEST_CODE = 42;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("ArkSigner", "onCreate called.");
deviceManager = getSystemService(CompanionDeviceManager.class);
// To skip filtering based on name and supported feature flags (UUIDs),
// don't include calls to setNamePattern() and addServiceUuid(),
// respectively. This example uses Bluetooth.
deviceFilter = new BluetoothDeviceFilter.Builder()
//.setNamePattern(Pattern.compile("Test"))
//.addServiceUuid(new ParcelUuid(new UUID(0x123abcL, -1L)), null)
.build();
// The argument provided in setSingleDevice() determines whether a single
// device name or a list of device names is presented to the user as
// pairing options.
pairingRequest = new AssociationRequest.Builder()
.addDeviceFilter(deviceFilter)
//.setSingleDevice(true)
.build();
List<String> associations = deviceManager.getAssociations();
// When the app tries to pair with the Bluetooth device, show the
// appropriate pairing request dialog to the user.
deviceManager.associate(pairingRequest,
new CompanionDeviceManager.Callback() {
@Override
public void onDeviceFound(IntentSender chooserLauncher) {
try {
Log.e("ArkSigner", "onDeviceFound called.");
startIntentSenderForResult(chooserLauncher,
SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(CharSequence error) {
Log.e("ArkSigner", "onFailure called.");
}
},
null);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("ArkSigner", "onActivityResult called.");
if (requestCode == SELECT_DEVICE_REQUEST_CODE &&
resultCode == Activity.RESULT_OK) {
// User has chosen to pair with the Bluetooth device.
BluetoothDevice deviceToPair =
data.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE);
deviceToPair.createBond();
// ... Continue interacting with the paired device.
}
}
}
运行我们的Android应用程序后,我们没有看到任何有关发现设备(蓝牙或BLE设备)的对话框。
编辑:如果我们在行“ .setNamePattern(Pattern.compile("Test"))”中提供设备名称或使用“ .setSingleDevice(true)”,它不会改变任何东西。