public AndroidBluetooth(BTCallback btCallback) { this.callback = btCallback; btManager = (BluetoothManager)MainActivity.MainContext.GetSystemService(Context.BluetoothService); btAdapter = btManager.Adapter; scanCallback = new MyScanCallback(this); bluetoothGattCallback = new MyGattCallback(this); // Watch for Bluetooth Power Changes btCheckThread = new Thread(new ThreadStart(() => { bool lastState = false; while (true && btAdapter != null) { bool state = btAdapter.IsEnabled; if (state != lastState) { lastState = state; if (!state) { endEnumeration(); disconnect(); } callback.onBluetoothPowerChanged(state); } Thread.Sleep(100); } })); btCheckThread.Start(); }
void IAdvertiseAndDiscoverBluetoothDevice.Discover() { try { Analytics.TrackEvent(Build.Model + " Discover method called."); List <ScanFilter> filters = new List <ScanFilter>(); ScanFilter filter = new ScanFilter.Builder() .SetServiceUuid(new ParcelUuid(MY_UUID)) .Build(); filters.Add(filter); //ScanSettings settings = new ScanSettings.Builder() // .SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency) // .Build(); ScanSettings.Builder builder = new ScanSettings.Builder(); builder.SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency); if (Build.VERSION.SdkInt >= BuildVersionCodes.M /* Marshmallow */) { builder.SetMatchMode(BluetoothScanMatchMode.Aggressive); builder.SetNumOfMatches((int)BluetoothScanMatchNumber.MaxAdvertisement); builder.SetCallbackType(ScanCallbackType.AllMatches); } var settings = builder.Build(); myScanCallback = new MyScanCallback(); bluetoothLeScanner = BluetoothAdapter.DefaultAdapter.BluetoothLeScanner; bluetoothLeScanner.StartScan(filters, settings, myScanCallback); } catch (System.Exception ex) { Analytics.TrackEvent(Build.Model + " Something went wrong in Discover method."); } }
public Adapter() { var appContext = Android.App.Application.Context; // get a reference to the bluetooth system service this._manager = (BluetoothManager)appContext.GetSystemService("bluetooth"); this._adapter = this._manager.Adapter; this._gattCallback = new GattCallback(this); _scanCallback = new MyScanCallback(this); this._gattCallback.DeviceConnected += (object sender, DeviceConnectionEventArgs e) => { this._connectedDevices.Add(e.Device); this.DeviceConnected(this, e); }; this._gattCallback.DeviceDisconnected += (object sender, DeviceConnectionEventArgs e) => { // TODO: remove the disconnected device from the _connectedDevices list // i don't think this will actually work, because i'm created a new underlying device here. //if(this._connectedDevices.Contains( this.DeviceDisconnected(this, e); }; }