Пример #1
0
        public async Task <bool> Connect(string deviceName)
        {
            if (!_bluetoothAdapter.Enable())
            {
                return(false);
            }

            try
            {
                var device = _bluetoothAdapter.GetRemoteDevice(deviceName);
                _bluetoothAdapter.CancelDiscovery();
                _btSocket = device.CreateRfcommSocketToServiceRecord(MyUuid);

                await _btSocket.ConnectAsync();

                if (_btSocket.IsConnected)
                {
                    Connected = true;
                }
            }
            catch (Exception ex)
            {
                Connected = false;
                var error = $"Cannot connect to bluetooth device ({deviceName}):, {ex.Message}, {ex.StackTrace}.";
                Log.Info(_tag, error);
            }

            return(Connected);
        }
Пример #2
0
        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;
            }
        }
Пример #3
0
 public void EnableIfNeeded(BluetoothAdapter adapter)
 {
     if (!adapter.IsEnabled)
     {
         adapter.Enable();
     }
 }
Пример #4
0
        protected override async void OnStart()
        {
            try
            {
                var hasPermission = await CheckGeolocationPermissions(Permission.Location);

                bluetoothBLE = CrossBluetoothLE.Current;
                var status = await EstimoteManager.Instance.Initialize();

                if (status == BeaconInitStatus.BluetoothOff || status == BeaconInitStatus.BluetoothMissing)
                {
                    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                    bluetoothAdapter.Enable();

                    EstimoteManager.Instance.Ranged += Instance_Ranged;
                    EstimoteManager.Instance.RegionStatusChanged += Instance_RegionStatusChanged;
                    EstimoteManager.Instance.StartRanging(new BeaconRegion("beacon_Ksec", EstimoteUuid));
                }
                else
                {
                    EstimoteManager.Instance.Ranged += Instance_Ranged;
                    EstimoteManager.Instance.RegionStatusChanged += Instance_RegionStatusChanged;
                    EstimoteManager.Instance.StartRanging(new BeaconRegion("beacon_Ksec", EstimoteUuid));
                }
            }
            catch (Exception ex)
            {
                await Current.MainPage.DisplayAlert("Atención", "La aplicacion no se puede ejecutar si no se encuentra hablilitado y/o disponible el Bluetooth", "Ok");

                System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
            }
        }
Пример #5
0
        private void TurnBluetoothOn()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            RunOnUiThread(() =>
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Confirmation");
                alert.SetMessage("Do you really want to turn Bluetooth On?");
                alert.SetPositiveButton("Yes", async(senderAlert, args) =>
                {
                    adapter.Enable();
                    await Task.Delay(2000);
                    if (adapter.IsEnabled)
                    {
                        Toast.MakeText(this, "Bluetooth Ready", ToastLength.Short).Show();
                        RequestDevices();
                    }
                });
                alert.SetNegativeButton("No", (senderAlert, args) => {
                    Toast.MakeText(this, "Cancelled", ToastLength.Short).Show();
                });
                Dialog dialog = alert.Create();
                dialog.Show();
            });
        }
Пример #6
0
        public string Check()
        {
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!mBluetoothAdapter.Enable())
            {
                var r1 = new BasicReturn()
                {
                    Flag = false, Code = "DIS", Message = "Bluetooth ไม่ได้เปิด!"
                };
                return(JsonConvert.SerializeObject(r1, Formatting.Indented));
            }

            if (mBluetoothAdapter == null)
            {
                var r2 = new BasicReturn()
                {
                    Flag = false, Code = "NUL", Message = "ไม่พบอุปกรณ์ Bluetooth!"
                };
                return(JsonConvert.SerializeObject(r2, Formatting.Indented));
            }

            // Good
            var r3 = new BasicReturn()
            {
                Flag = true, Code = "00", Message = "Bluetooth เปิดให้ใช้งานแล้ว"
            };

            return(JsonConvert.SerializeObject(r3, Formatting.Indented));
        }
Пример #7
0
 private void Button_BT_TurnOn(object sender, EventArgs e)
 {
     if (!_manager.IsEnabled)
     {
         _manager.Enable();
     }
 }
Пример #8
0
        /// <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);
            }
        }
Пример #9
0
        protected override async void OnAppearing()
        {
            await connection.CreateTableAsync <TimeInPunches>();

            var myTimes = await connection.Table <TimeInPunches>().ToListAsync();

            myTimeIns   = new ObservableCollection <TimeInPunches>(myTimes);
            myTimeOuts  = new ObservableCollection <TimeInPunches>(myTimes);
            myDevices   = new ObservableCollection <IDevice>();
            deviceNames = new ObservableCollection <string>();   //Collects ID, RSSI, Time records

            TimeInList.ItemsSource = myTimeIns;

            DeviceList.ItemsSource = deviceNames;

            if (!mBluetoothAdapter.IsEnabled)
            {
                var result = await DisplayAlert("Bluetooth Acivation", "This device will require bluetooth activation, may I activate bluetooth?", "Ok", "No");

                if (result)
                {
                    mBluetoothAdapter.Enable();
                }
            }

            base.OnAppearing();
        }
        private async void ScanOnClick(object sender, EventArgs eventArgs)
        {
            _bluetoothDevices = new ObservableCollection <BluetoothDevice>();
            _pickedDevice     = null;

            _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            if (_bluetoothAdapter == null)
            {
                Toast.MakeText(this, "Wrong device", ToastLength.Short).Show();
                return;
            }
            if (!_bluetoothAdapter.IsEnabled)
            {
                _bluetoothAdapter.Enable();
            }

            _bluetoothAdapter.StartDiscovery();

            await Task.Run(() =>
            {
                Task.Delay(2000);
                _bluetoothAdapter.CancelDiscovery();
            });

            var pairedDevices = _bluetoothAdapter.BondedDevices;

            foreach (var pairedDevice in pairedDevices)
            {
                _bluetoothDevices.Add(pairedDevice);
            }
            _devicesList.Adapter = new BluetoothsAdapter(_bluetoothDevices);
        }
        private async Task FirstScan()
        {
            _busyIndicator.Visibility             = ViewStates.Visible;
            _busyIndicatorLinearLayout.Visibility = ViewStates.Visible;

            await Task.Delay(500);

            _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (_bluetoothAdapter == null)
            {
                return;
            }

            if (!_bluetoothAdapter.IsEnabled)
            {
                _wasBluetoothEnabled = false;
                await Task.Run(async() =>
                {
                    _bluetoothAdapter.Enable();
                    await Task.Delay(2000);
                });
            }
            var pairedDevices = _bluetoothAdapter.BondedDevices;

            foreach (var pairedDevice in pairedDevices)
            {
                _bluetoothDevices.Add(pairedDevice);
            }
            _devicesList.Adapter      = new BluetoothsAdapter(_bluetoothDevices);
            _busyIndicator.Visibility = ViewStates.Gone;
        }
Пример #12
0
        //Evento de conexion al Bluetooth
        public void Connect()
        {
            //asignamos el sensor bluetooth con el que vamos a trabajar
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            //Verificamos que este habilitado
            if (!mBluetoothAdapter.Enable())
            {
                Toast.MakeText(this, "Bluetooth Desactivado",
                               ToastLength.Short).Show();
            }
            //verificamos que no sea nulo el sensor
            if (mBluetoothAdapter == null)
            {
                Toast.MakeText(this,
                               "Bluetooth No Existe o esta Ocupado", ToastLength.Short)
                .Show();
            }

            //Iniciamos la conexion con el arduino
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            System.Console.WriteLine("Conexion en curso" + device);

            //Indicamos al adaptador que ya no sea visible
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                //Inicamos el socket de comunicacion con el arduino
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                //Conectamos el socket
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                //en caso de generarnos error cerramos el socket
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }

            //Una vez conectados al bluetooth mandamos llamar el metodo que generara el hilo
            //que recibira los datos del arduino
            beginListenForData();
            //NOTA envio la letra e ya que el sketch esta configurado para funcionar cuando
            //recibe esta letra.

            //dataToSend = new Java.Lang.String("Hola");
            //writeData(dataToSend);
        }
Пример #13
0
        public void BuletoothEnable()
        {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!bluetoothAdapter.IsEnabled)
            {
                bluetoothAdapter.Enable();
            }
        }
Пример #14
0
        private void CheckBt()
        {
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (mBluetoothAdapter != null && mBluetoothAdapter.Enable())
            {
                Connect("c");
            }
        }
Пример #15
0
        //--------------  Public  METHODS   -------------------------------------------------------------------------------------

        public async void DoTurnOn()
        {
            if (!_btAdapter.IsEnabled && _btAdapter != null)
            {
                await _page.DisplayAlert("Action", "Bluetooth Turned On", "OK");

                _btAdapter.Enable();
            }
        }
        public void EnableBluetooth()
        {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (bluetoothAdapter.IsEnabled == false)
            {
                bluetoothAdapter.Enable();
            }
        }
Пример #17
0
        /// <summary>
        /// Включение bluetooth
        /// </summary>
        private void TurnOnBluetooth()
        {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!bluetoothAdapter.IsEnabled)
            {
                bluetoothAdapter.Enable();
            }
        }
Пример #18
0
        private void InitializeBluetooth()
        {
            adapter = BluetoothAdapter.DefaultAdapter;

            if (!adapter.IsEnabled)
            {
                adapter.Enable();
            }
        }
Пример #19
0
 public void StartScan()
 {
     if (!this._adapter.IsEnabled)
     {
         _adapter.Enable();
     }
     //_rssiThreshold = rssiOption;
     this._count = 0;
     this._adapter.StartLeScan(this);
 }
Пример #20
0
        void OnBluetoothEnableClick(object sender, EventArgs e)
        {
            if (!bt.Enable())
            {
                Intent enable = new Intent(BluetoothAdapter.ActionRequestEnable);
                StartActivityForResult(enable, 0);
            }

            Toast.MakeText(this, "Bluetooth Enabled", ToastLength.Short).Show();
        }
Пример #21
0
        private void FindBTPrinter()
        {
            string printername = apara.PrinterName.Trim().ToUpper();

            try{
                mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

                if (mBluetoothAdapter == null)
                {
                    msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound);
                    return;
                }
                string txt = "";
                if (!mBluetoothAdapter.Enable())
                {
                    Intent enableBluetooth = new Intent(
                        BluetoothAdapter.ActionRequestEnable);
                    StartActivityForResult(enableBluetooth, 0);
                }

                var pair = mBluetoothAdapter.BondedDevices;
                if (pair.Count > 0)
                {
                    foreach (BluetoothDevice dev in pair)
                    {
                        Console.WriteLine(dev.Name);
                        txt = txt + "," + dev.Name;
                        if (dev.Name.ToUpper() == printername)
                        {
                            mmDevice = dev;
                            //							File.WriteAllText(addrfile,dev.Address);
                            break;
                        }
                    }
                }
                msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothfound) + mmDevice.Name;
            }catch {
                //txtv.Text = ex.Message;
                mmDevice = null;
                msg      = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound);
                //AlertShow(ex.Message);
            }finally {
                if (mBluetoothAdapter != null)
                {
                    if (mBluetoothAdapter.IsDiscovering)
                    {
                        mBluetoothAdapter.CancelDiscovery();
                        Thread.Sleep(300);
                    }

                    mBluetoothAdapter.Dispose();
                    mBluetoothAdapter = null;
                }
            }
        }
Пример #22
0
        public int EnableBluetooth()
        {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!mBluetoothAdapter.IsEnabled)
            {
                mBluetoothAdapter.Enable();
                return(1);
            }
            return(0);
        }
Пример #23
0
        public bool TurnOn()
        {
            BluetoothAdapter b = BluetoothAdapter.DefaultAdapter;

            if (b.IsEnabled)
            {
                return(true);
            }
            b.Enable();
            return(false);
        }
Пример #24
0
 /// <summary>
 /// Enables the bluetooth.
 /// </summary>
 public void enableBluetooth()
 {
     //if bluetooth is already enabled returns
     if (_btAdapter.IsEnabled)
     {
         return;
     }
     //else enable bluetooth
     _btAdapter.Enable();
     //make it visible
     makeVisible();
 }
Пример #25
0
        private void CheckBt()
        {
            btAdapter = BluetoothAdapter.DefaultAdapter;

            if (!btAdapter.Enable())
            {
                Toast.MakeText(this, "Bluetooth Desactivado", ToastLength.Short).Show();
            }
            if (btAdapter == null)
            {
                Toast.MakeText(this, "Bluetooth No Existe o esta Ocupado", ToastLength.Short).Show();
            }
        }
Пример #26
0
        public void CheckBluetooth()
        {
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!mBluetoothAdapter.Enable())
            {
                UserDialogs.Instance.Alert("Bluetooth Deactivated!");
            }
            if (mBluetoothAdapter == null)
            {
                UserDialogs.Instance.Alert("Bluetooth Not Existing!");
            }
        }
Пример #27
0
        private static bool TryTurnOnBluetooth()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                return(false);
            }
            if (!adapter.IsEnabled)
            {
                adapter.Enable();
            }
            return(adapter.IsEnabled);
        }
        //este método no está incluido porque solo se trata de un dispositivo y ya de hecho conocido
        //lo incluí para futuras consideraciones o escenarios más complejos.
        private void CheckBluetoothDevice()
        {
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!mBluetoothAdapter.Enable())
            {
                Toast.MakeText(this, "Bluetooth disabled", ToastLength.Short).Show();
            }

            if (mBluetoothAdapter == null)
            {
                Toast.MakeText(this, "Bluetooth device is occupied or non-existant", ToastLength.Short).Show();
            }
        }
 public void TrySetBleEnabled(bool enabled)
 {
     if (bluetoothAdapter.IsEnabled != enabled)
     {
         if (enabled == false)
         {
             bluetoothAdapter.Disable();
         }
         else
         {
             bluetoothAdapter.Enable();
         }
     }
 }
Пример #30
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            if (!(ContextCompat.CheckSelfPermission(this, locationPermission) == (int)Permission.Granted))
            {
                ActivityCompat.RequestPermissions(this, new String[] { locationPermission, locationfinePermission, bluetoothPermission, bluetoothadminPermission, wifiPermission, changewifiPermission }, requestPermissions);
            }

            bluetoothAdapter.Enable();

            bluetoothAdapter.StartDiscovery();

            BluetoothDeviceReceiver bluetoothDeviceReceiver = new BluetoothDeviceReceiver();

            RegisterReceiver(bluetoothDeviceReceiver, new IntentFilter(BluetoothDevice.ActionFound));

            WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.WifiService);

            wifiManager.StartScan();

            WifiReceiver wifiReceiver = new WifiReceiver();

            RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));

            /*var networks = wifiManager.ConfiguredNetworks;
             * string wifi = "";
             *
             * for (int i = 0; i < networks.Count; i++)
             * {
             *  wifi = wifi + networks[i].Ssid + "\r\n";
             *  DisplayTextWifi(wifi);
             * }*/


            /*string networkSSID = "WIFI-GUEST";
             * string networkPass = "";
             *
             * WifiConfiguration wifiConfig = new WifiConfiguration();
             * wifiConfig.Ssid = string.Format("\"{0}\"", networkSSID);
             * wifiConfig.PreSharedKey = string.Format("\"{0}\"", networkPass);
             *
             * int netId = wifiManager.AddNetwork(wifiConfig);
             * wifiManager.Disconnect();
             * wifiManager.EnableNetwork(netId, true);
             * wifiManager.Reconnect();*/
        }