Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Bluetooth Bonded devices is not working in xamarin forms

I am binding a list with Bluetooth Bonded devices and before it I am enabling Bluetooth with my codes. But the problem is that it is not working first time, it is working on 2nd time of my search button click. Also when I am first enabling the Bluetooth manually from the setting and then click on search button it is also working. The main miracle is that when I am using breakpoint on the method and go with step by step than it is working. Till last day it was Woking fine but what happen now it is not working. I am sharing my code. Thanks for help...

///interface class

 public interface IBlueToothService
{
  public ObservableCollection<string> GetDeviceList();
  public  Task Print(string deviceName, string text);

}

//native android dependency class

   [assembly: Xamarin.Forms.Dependency(typeof(AndroidBlueToothService))]
   namespace R1Soft_App.Droid.DependencyServices
  {
class AndroidBlueToothService : IBlueToothService
{


    public ObservableCollection<string> GetDeviceList()
    {
        using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
        {
            if (bluetoothAdapter.IsEnabled == false)
            {
                bluetoothAdapter.Enable();
            }

            var btdevice = bluetoothAdapter?.BondedDevices.Select(i => i.Name).OrderBy(x => 
         x).ToList();

            return new ObservableCollection <string>(btdevice);
        }
    }


    public async Task Print(string deviceName, string text)
    {
        UserDialogs.Instance.ShowLoading();

        using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
        {
            if (bluetoothAdapter.IsEnabled == false)
            {
                bluetoothAdapter.Enable();
            }
            BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
                                      where bd?.Name == deviceName
                                      select bd).FirstOrDefault();              
            try
            {
                using (BluetoothSocket bluetoothSocket = device?.
                    CreateRfcommSocketToServiceRecord(
                    UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
                {
                    bluetoothSocket?.Connect();
                    byte[] buffer = Encoding.UTF8.GetBytes(text);
                    bluetoothSocket?.OutputStream.Write(buffer, 0, buffer.Length);
                    bluetoothSocket.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            UserDialogs.Instance.HideLoading();

        }
    }
}

}

//view model code

    private readonly IBlueToothService blueToothService;

    public AddPrinterViewModel()
    {
        try
        {

            blueToothService = DependencyService.Get<IBlueToothService>();             
        } 
        catch(Exception ex)
        {
             App.Current.MainPage.DisplayAlert("Alert", ex.Message.ToString(), "Ok");
        }

    }

   public ObservableCollection<string> deviceList = new ObservableCollection<string>();
    public ObservableCollection<string> DeviceList
    {
        get
        {
            return deviceList;
        }
        set
        {
            deviceList = value;
            OnPropertyChanged(nameof(DeviceList));
        }
    }


    private Command searchCommand;
    public  Command SearchCommand
    {
        get { return searchCommand ?? (searchCommand = new Command(() =>  ExecuteSearchCommand())); }
    }

    public async void ExecuteSearchCommand()
    {

        try
        {    
            var list = blueToothService.GetDeviceList();
            DeviceList = list;             
        }

        catch (Exception ex)
        {
           await  App.Current.MainPage.DisplayAlert("Alert", ex.Message.ToString(), "Ok");
        }
        UserDialogs.Instance.HideLoading();


    }
Sign In or Register to comment.