Hello,
Thanks for your feedback.
In accordance with the forum's privacy policy, I removed the link to the sample project.
After testing, you can follow the steps below to implement the Bluetooth scanning function.
Step 1. Add these relevant permissions in your Android manifest.
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Android 12 must add android:usesPermissionFlags="neverForLocation" when not applying for location permission, otherwise the devices will not be found -->
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
Step 2. Dynamically request for permissions in the MainActivity
.
public class MainActivity : MauiAppCompatActivity
{
private const int REQUEST_PERMISSION_CODE = 1001;
protected override void OnCreate(Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
initPermission();
}
private void initPermission()
{
List<String> mPermissionList = new List<string>();
// When the Android version is 12 or greater, apply for new Bluetooth permissions
if (Build.VERSION.SdkInt >= BuildVersionCodes.S)
{
mPermissionList.Add(Manifest.Permission.BluetoothScan);
mPermissionList.Add(Manifest.Permission.BluetoothAdvertise);
mPermissionList.Add(Manifest.Permission.BluetoothConnect);
//Request for location permissions based on your actual needs
//mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
else
{
mPermissionList.Add(Manifest.Permission.AccessCoarseLocation);
mPermissionList.Add(Manifest.Permission.AccessFineLocation);
}
ActivityCompat.RequestPermissions(this, mPermissionList.ToArray(), REQUEST_PERMISSION_CODE);
}
}
Step 3. Invoke scan function.
var adapter = CrossBluetoothLE.Current.Adapter;
var state = ble.State;
adapter.ScanTimeout = 20000;
//await RequestBluetooth();
await adapter.StartScanningForDevicesAsync(); // Add this line before the applicaiton can get the list of Bluetooth devices.
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.