/// <summary> /// Ativa o bluetooth /// </summary> /// <param name="enable">Ativar (true) | Desativar (false)</param> /// <returns></returns> public static bool TurnOnBluetooth(bool enable) { try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (bluetoothAdapter == null) { return(false); } if (enable && !bluetoothAdapter.IsEnabled) { return(bluetoothAdapter.Enable()); } else if (!enable && bluetoothAdapter.IsEnabled) { return(bluetoothAdapter.Disable()); } return(true); } catch { return(false); } }
public void DisableBluetooth() { if (_btAdapter.IsEnabled) { _btAdapter.Disable(); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Connection); btnstart = FindViewById <Button>(Resource.Id.startButton); btnstart.Click += Btnstart_Click; btnstop = FindViewById <Button>(Resource.Id.stopButton); btnstop.Click += Btnstop_Click; //Debug txtDebug = FindViewById <TextView>(Resource.Id.debugLog); Button backToMain = FindViewById <Button>(Resource.Id.backToMainFromConnection); backToMain.Click += (sender, e) => { try { BluetoothAdapter defaultAdapter = BluetoothAdapter.DefaultAdapter; if (defaultAdapter.IsEnabled) { defaultAdapter.Disable(); } var intent = new Intent(this, typeof(MainActivity)); StartActivity(intent); } catch (Exception exc) { Console.WriteLine(exc); } }; }
private void Button_BT_TurnOff(object sender, EventArgs e) { if (_manager.IsEnabled) { _manager.Disable(); } }
public override void OnBackPressed() { base.OnBackPressed(); if (!_wasBluetoothEnabled) { _bluetoothAdapter.Disable(); } }
private void Btnstop_Click(object sender, EventArgs e) { BluetoothAdapter defaultAdapter = BluetoothAdapter.DefaultAdapter; if (defaultAdapter.IsEnabled) { defaultAdapter.Disable(); } }
public int DisableBluetooth() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (mBluetoothAdapter.IsEnabled) { mBluetoothAdapter.Disable(); } return(1); }
//returns the current state of the Bluetooth adapter public bool TurnOff() { BluetoothAdapter b = BluetoothAdapter.DefaultAdapter; if (!b.IsEnabled) { return(false); //Bluetooth was off } b.Disable(); return(true); }
public void Disconnect() { BluetoothAdapter defaultAdapter = BluetoothAdapter.DefaultAdapter; if (defaultAdapter.IsEnabled) { ProgressAction("Bluetooth disconnecting"); defaultAdapter.Disable(); ProgressAction("Bluetooth disconnected"); } }
public void OnClick(View v) { switch (v.Id) { case Resource.Id.onB: if (!blue.Enable()) { Intent o = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(o, 0); } Toast.MakeText(this, "Enable", ToastLength.Short).Show(); break; case Resource.Id.offB: if (blue.Enable()) { blue.Disable(); Toast.MakeText(this, "Bluetooth Disable", ToastLength.Short).Show(); } break; // case Resource.Id.visibleD: // Intent visible = new Intent(BluetoothAdapter.ActionsRequestDiscoverable)' // StartActivityForResult(visible, 0); //break; case Resource.Id.pairD: ArrayList list = new ArrayList(); foreach (BluetoothDevice bt in blue.BondedDevices) { list.Add(bt.Name); } ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, list); list_Of_Devices.SetAdapter(adapter); break; //case Resource.Id.nameBtn: // if (!bluetoothName.Text.ToString().Equals("")) // { // String n = bluetoothName.Text.Tostring(); // blue.SetName(n); // } // else // { // Toast.MakeText(this, "Please enter name", ToastLength.Short).Show(); // } // break; case Resource.Id.showName: Toast.MakeText(this, blue.Name.ToString(), ToastLength.Short).Show(); break; } }
public async void DoTurnOff() { if (_btAdapter.IsEnabled || _btSocket.IsConnected) { await DoCloseDispose(_btAdapter); await DoCloseDispose(_btSocket); _btAdapter.Disable(); _btSocket.Close(); await _page.DisplayAlert("Action", "Socket and Bluetooth turned Off", "OK"); } }
public void Cancel() { try { mSocket.Close(); btAdapter.Disable(); //streamList.Clear(); //deviceList.Clear(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Could not close the connect socket", ex); } }
public void TrySetBleEnabled(bool enabled) { if (bluetoothAdapter.IsEnabled != enabled) { if (enabled == false) { bluetoothAdapter.Disable(); } else { bluetoothAdapter.Enable(); } } }
private void _bTSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { if (!_bluetoothAdapter.IsEnabled) { _bluetoothAdapter.Enable(); } } else { StopSearch(); _bluetoothAdapter.Disable(); AccessReadBtn.Enabled = false; } }
private void SetMode(RadioMode value) { switch (value) { case RadioMode.PowerOff: _adapter.Disable(); break; default: // TODO: Determine if setting ScanMode is possible if (!_adapter.IsEnabled) { _adapter.Enable(); } break; } }
private void TurnOffBluetooth() { btSwitch.Text = "Turn Bluetooth On"; if (btAdapter == null) { // message tayo dito device doesn't support bluetooth Logger.Log("Device doesn't support Bluetooth"); return; } // enabled, so we turn it off if (btAdapter.IsEnabled) { btAdapter.Disable(); Intent enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(enableIntent, REQUEST_ENABLE_BT); } }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (bluetoothAdapter.IsEnabled == false) { bluetoothAdapter.Enable(); } else { bluetoothAdapter.Disable(); } }
// @see https://stackoverflow.com/a/43754366/11615696 public bool enableBluetooth(bool flag) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; var enabled = bluetoothAdapter.IsEnabled; if (flag == enabled) { logger.debug($"enableBluetooth: naught to do! ({flag})"); return(true); } logger.debug($"enableBluetooth: setting {flag}"); if (flag) { bluetoothAdapter.Enable(); } else { bluetoothAdapter.Disable(); } return(true); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (mBluetoothAdapter == null) { // Device does not support Bluetooth } if (!mBluetoothAdapter.IsEnabled) { Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable); int REQUEST_ENABLE_BT = 0; StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } // Register for broadcasts when a device is discovered receiver = new Receiver(this); var filter = new IntentFilter(BluetoothDevice.ActionFound); RegisterReceiver(receiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished); RegisterReceiver(receiver, filter); // Register for broadcasts when a device tries to pair filter = new IntentFilter(BluetoothDevice.ActionPairingRequest); RegisterReceiver(receiver, filter); // Get the local Bluetooth adapter btAdapter = BluetoothAdapter.DefaultAdapter; var scanButton = FindViewById <Button>(Resource.Id.button1); scanButton.Click += (sender, e) => { char[] blank = new char[1]; FindViewById <TextView>(Resource.Id.textView2).SetText(blank, 0, 0); receiver.HC05Found = false; DoDiscovery(); }; var aboutButton = FindViewById <Button>(Resource.Id.button2); aboutButton.Click += (sender, e) => { About(this); }; var closeButton = FindViewById <Button>(Resource.Id.button3); closeButton.Click += (sender, e) => { mBluetoothAdapter.Disable(); this.FinishAffinity(); }; }
public override bool DisableBluetooth(bool reenable, bool lowEnergy = true, string rationale = null) { base.DisableBluetooth(reenable, lowEnergy, rationale); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; // check whether bluetooth is enabled if (bluetoothAdapter?.IsEnabled ?? false) { ManualResetEvent disableWait = new ManualResetEvent(false); ManualResetEvent enableWait = new ManualResetEvent(false); EventHandler <global::Android.Bluetooth.State> StateChangedHandler = (sender, newState) => { if (newState == global::Android.Bluetooth.State.Off) { disableWait.Set(); } else if (newState == global::Android.Bluetooth.State.On) { enableWait.Set(); } }; AndroidBluetoothBroadcastReceiver.STATE_CHANGED += StateChangedHandler; try { if (!bluetoothAdapter.Disable()) { disableWait.Set(); } } catch (Exception) { disableWait.Set(); } disableWait.WaitOne(5000); if (reenable) { try { if (!bluetoothAdapter.Enable()) { enableWait.Set(); } } catch (Exception) { enableWait.Set(); } enableWait.WaitOne(5000); } AndroidBluetoothBroadcastReceiver.STATE_CHANGED -= StateChangedHandler; } bool isEnabled = bluetoothAdapter?.IsEnabled ?? false; // dispatch an intent to reenable bluetooth, which will require user interaction. if (reenable && !isEnabled) { return(EnableBluetooth(lowEnergy, rationale)); } else { return(isEnabled); } }
public static void Disable() { adapter.Disable(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); mStatusTv = (TextView)FindViewById(Resource.Id.tv_status); mActivateBtn = (Button)FindViewById(Resource.Id.btn_enable); mPairedBtn = (Button)FindViewById(Resource.Id.btn_view_paired); mScanBtn = (Button)FindViewById(Resource.Id.btn_scan); mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; mProgressDlg = new ProgressDialog(this); mProgressDlg.SetMessage("Scanning..."); mProgressDlg.SetCancelable(false); IntentFilter filter = new IntentFilter(); filter.AddAction(BluetoothAdapter.ActionStateChanged); filter.AddAction(BluetoothDevice.ActionFound); filter.AddAction(BluetoothAdapter.ActionDiscoveryStarted); filter.AddAction(BluetoothAdapter.ActionDiscoveryFinished); broadcastReceiver = new BluetoothBroadcastReceiver(() => { showToast("Enabled"); showEnabled(); }, () => { mProgressDlg.Show(); }, mDeviceList); RegisterReceiver(broadcastReceiver, filter); if (mBluetoothAdapter == null) { showUnsupported(); } else { mPairedBtn.Click += (sender, e) => { var pairedDevices = mBluetoothAdapter.BondedDevices; if (pairedDevices == null || pairedDevices.Count == 0) { showToast("No Paired Devices Found"); } else { IList <IParcelable> list = new List <IParcelable>(); foreach (var device in pairedDevices) { list.Add(device); } Intent intent = new Intent(this, typeof(DeviceListActivity)); intent.PutParcelableArrayListExtra("device.list", list); StartActivity(intent); } }; mScanBtn.Click += (sender, e) => { if (mBluetoothAdapter.IsDiscovering) { // cancel the discovery if it has already started mBluetoothAdapter.CancelDiscovery(); } if (mBluetoothAdapter.StartDiscovery()) { // bluetooth has started discovery } }; mActivateBtn.Click += (sender, e) => { if (mBluetoothAdapter.IsEnabled) { mBluetoothAdapter.Disable(); showDisabled(); } else { Intent intent = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(intent, 1000); } }; if (mBluetoothAdapter.IsEnabled) { showEnabled(); } else { showDisabled(); } } }
private async void Request_AccessAsync(object sender, EventArgs e) { byte[] buffer = new byte[256]; MySqlConnection myConn = new MySqlConnection(Resources.GetString(Resource.String.myConnectionString)); if (myConn.State == System.Data.ConnectionState.Closed) { myConn.Open(); // connection timeout is set to 60 ,check strings.xml } string access_code = Login.GetPass(); //storing password in order to check the access code with arduino string numberCar = Login.GetNumberCar(); // this will be set if the user has a car //check if bluetooth is on if (!(adapter.IsEnabled)) { Console.WriteLine("Enabling bluetooth"); Toast.MakeText(ApplicationContext, "Enabling bluetooth first", ToastLength.Long).Show(); adapter.Enable(); Thread.Sleep(2000); // if bluetooth is not up } // this will connect to bluetooth if (adapter == null) { throw new Exception("No bluetooth adapter found."); } if (!adapter.IsEnabled) { throw new Exception("Bluetooth adapter is not enabled"); } BluetoothDevice device = (from bd in this.adapter.BondedDevices where bd.Name == "HC-05" select bd).FirstOrDefault(); Console.WriteLine("\n\n" + device.Name); if (device == null) { throw new Exception("Named device not found."); } _socket = CreateRfcommSocket(device); // used another function for creating the socket Console.WriteLine(device.GetUuids().ToString()); string InsertSql = "Update Angajat_Intrare SET Marca=@marca, Nume=@nume, Prenume=@prenume, Poza=@poza, Divizia=@divizie"; MySqlCommand cmdInsert = new MySqlCommand(InsertSql, myConn); cmdInsert.Parameters.AddWithValue("@marca", Login.GetUser()); cmdInsert.Parameters.AddWithValue("@nume", Login.GetNume()); cmdInsert.Parameters.AddWithValue("@prenume", Login.GetPrenume()); cmdInsert.Parameters.AddWithValue("@poza", null); cmdInsert.Parameters.AddWithValue("@divizie", Login.GetDivizie()); cmdInsert.ExecuteNonQuery(); cmdInsert.Dispose(); try { await _socket.ConnectAsync(); Toast.MakeText(ApplicationContext, "Connected with bluetooth", ToastLength.Short).Show(); // Write data to the device await _socket.OutputStream.WriteAsync(Encoding.ASCII.GetBytes(access_code)); //send Marca Console.WriteLine("Access code sent..."); //var receivedString = Encoding.UTF8.GetString(buffer); //convert the bytes received to string //Console.WriteLine($"Converted string is {receivedString}"); //if(receivedString.Equals("Yes")) // Toast.MakeText(ApplicationContext, "Access Granted", ToastLength.Short).Show(); //arduino will lift the barrier } catch (Exception ex) { Toast.MakeText(ApplicationContext, "couldn't connect with bluetooth", ToastLength.Short).Show(); Console.WriteLine("\n\n Error is -- " + ex.ToString() + "\n\n"); // this is the function that overwrites the socket in case of failure } finally { adapter.Disable(); // disable bluetooth _socket.Close(); //closing communication socket } }
public override async Task <bool> DisableBluetoothAsync(bool reenable, bool lowEnergy = true, string rationale = null) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; // check whether bluetooth is enabled if (bluetoothAdapter?.IsEnabled ?? false) { TaskCompletionSource <State> bluetoothStateChangedCompletionSource = new TaskCompletionSource <State>(); EventHandler <State> StateChangedHandler = (sender, newState) => { if (newState == State.On || newState == State.Off) { bluetoothStateChangedCompletionSource.TrySetResult(newState); } }; AndroidBluetoothBroadcastReceiver.STATE_CHANGED += StateChangedHandler; try { if (!bluetoothAdapter.Disable()) { bluetoothStateChangedCompletionSource.TrySetResult(State.On); } } catch (Exception) { bluetoothStateChangedCompletionSource.TrySetResult(State.On); } await bluetoothStateChangedCompletionSource.Task; // try to reenable without user interaction -- may not be allowed. if (reenable) { bluetoothStateChangedCompletionSource = new TaskCompletionSource <State>(); try { if (!bluetoothAdapter.Enable()) { bluetoothStateChangedCompletionSource.TrySetResult(State.Off); } } catch (Exception) { bluetoothStateChangedCompletionSource.TrySetResult(State.Off); } await bluetoothStateChangedCompletionSource.Task; } AndroidBluetoothBroadcastReceiver.STATE_CHANGED -= StateChangedHandler; } bool isEnabled = bluetoothAdapter?.IsEnabled ?? false; // dispatch an intent to reenable bluetooth, which will require user interaction. if (reenable && !isEnabled) { return(await EnableBluetoothAsync(lowEnergy, rationale)); } else { return(isEnabled); } }
public async Task <List <BluetoothDevice> > FetchResultsAsync() { var running = true; var discoveryCanceled = false; while (running) { await new Select { Case(ChannelFactory.Timeout(TimeSpan.FromSeconds(30)), async() => { Console.WriteLine("Watchdog timeout at discovery!"); adapter.CancelDiscovery(); Console.WriteLine("Adapter enabled: " + adapter.IsEnabled); Console.WriteLine("Disabling adapter..."); adapter.Disable(); await Task.Delay(5000); Console.WriteLine("Enabling adapter..."); adapter.Enable(); await Task.Delay(10000); running = false; }), Case(intentChannel, intent => { Console.WriteLine($"GOT INTENT: " + intent.Action); var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); switch (intent.Action) { case BluetoothAdapter.ActionDiscoveryStarted: if (state != 0) { Console.WriteLine("WARN: STATE IS " + state + " NOT 0"); } state = 1; Console.WriteLine($"Started Discovery"); break; case BluetoothDevice.ActionFound: if (state != 1 && state != 2) { Console.WriteLine("WARN: STATE IS " + state + " NOT 1 or 2"); } state = 2; Console.WriteLine($"Found: {device.Address} {device.Name ?? "[no name]"}"); if (device.Name == null) { Console.WriteLine("Skip as no name!"); return; } allDiscoveredDevicesByMac.TryAdd(device.Address, device); break; case BluetoothAdapter.ActionDiscoveryFinished: if (state != 2) { Console.WriteLine("WARN: STATE IS " + state + " NOT 2"); return; } state = 3; Console.WriteLine($"Finished Discovery, Performing Service Discovery for Filtering"); adapter.CancelDiscovery(); allDiscoveredDevicesByMac.ForEach(kvp => pendingServiceDiscoveryDevices.AddOrThrow(kvp.Value)); running = TriggerNextServiceDiscoveryElseCompletion(); break; case BluetoothDevice.ActionUuid: if (state != 3 && state != 4) { Console.WriteLine("WARN: STATE IS " + state + " NOT 3 or 4"); } state = 4; Console.WriteLine($"Got UUIDs of device {device.Address} {device.Name ?? "[no name]"}"); var uuidObjects = intent.GetParcelableArrayExtra(BluetoothDevice.ExtraUuid); if (uuidObjects != null) { var uuids = uuidObjects.Cast <ParcelUuid>().ToArray(); uuids.ForEach(Console.WriteLine); // Equality isn't implemented by uuid, so compare tostrings... if (uuids.Any(uuid => uuid.ToString().Equals(CampfireNetBluetoothConstants.APP_UUID.ToString())) || uuids.Any(uuid => uuid.ToString().Equals(CampfireNetBluetoothConstants.FIRMWARE_BUG_REVERSE_APP_UUID.ToString()))) { Console.WriteLine($"Found CampfireNet device {device.Address} {device.Name ?? "[no name]"}"); BluetoothDevice existing; if (discoveredCampfireNetDevices.TryGetValue(device.Address, out existing)) { Console.WriteLine("Device already discovered!"); } else { discoveredCampfireNetDevices.TryAdd(device.Address, device); } } } if (!allDiscoveredDevicesByMac.ContainsKey(device.Address)) { Console.WriteLine("Unrequested UUID, so tossing"); return; } if (serviceDiscoveredDevicesByMac.TryAdd(device.Address, device)) { running = TriggerNextServiceDiscoveryElseCompletion(); } break; default: throw new NotImplementedException($"Unhandled intent action: {intent.Action}"); } }) }.ConfigureAwait(false); } Console.WriteLine("Returning discovered list. Count: " + discoveredCampfireNetDevices.Values.ToList().Count); return(discoveredCampfireNetDevices.Values.ToList()); }
public void Disable() => _bluetoothAdapter?.Disable();