0
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Android.Content;
using Android.Views;

namespace BluetoothBLE
{
[Activity(Label = "BluetoothBLE", MainLauncher = true)]
public class MainActivity : Activity
{
    //Local Bluetooth adapter
    private BluetoothAdapter bluetoothAdapter = null;

    //Return Intent extra
    public const string Extra_Device_Address = "device_address";

    //Members Field
    private static ArrayAdapter<string> Device;

    protected override void OnCreate(Bundle savedInstanceState) 
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        //Get our UI controls from the loaded layout
        TextView Text = FindViewById<TextView>(Resource.Id.BluetoothDevices);
        TextView Device_Name = FindViewById<TextView>(Resource.Id.DeviceName);
        Button Scan = FindViewById<Button>(Resource.Id.Scan);
        TextView NewDevice = FindViewById<TextView>(Resource.Id.NewDevice);
        ListView List = FindViewById<ListView>(Resource.Id.ListBluetooth);

        //Initialize array adapters
        Device = new ArrayAdapter<string>(this, Resource.Layout.Main);

        //Testing Faced
        Scan.Click += (sender, e) =>
        {
            if (bluetoothAdapter.IsEnabled == true)
            {
                Toast.MakeText(Application, "Start scanning",      ToastLength.Short).Show();
                DoDiscovery();
                (sender as View).Visibility = ViewStates.Visible;
                if(Device.Count != 0)
                {
                    NewDevice.Text = Device.GetItem(0).ToString();
                }
                else
                {
                    NewDevice.Text = "Device is not recorded";
                }
                Toast.MakeText(Application, "Device found", ToastLength.Short).Show();
            }
            else
            {
                Toast.MakeText(Application, "Please enable bluetooth", ToastLength.Short).Show();
            }

        };

        //Find and set up the ListView for newly discovered devices.
        List.Adapter = Device;
        List.ItemClick += DeviceListClick;

        //Register for broadcasts when a device is discovered
        Receiver receiver = new Receiver();
        var filter = new IntentFilter(BluetoothDevice.ActionFound);
        RegisterReceiver(receiver, filter);

        //Register for broadcasts when discovery is finished
        filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished);
        RegisterReceiver(receiver, filter);

        bluetoothAdapter = BluetoothAdapter.DefaultAdapter; //Get Loacl Bluetooth Adapter

        if (bluetoothAdapter == null)
        {
            Toast.MakeText(this, "Bluetooth is not Supported.", ToastLength.Long).Show();
            Finish();
            return;
        }

        //Display the Name of local bluetooth
        Device_Name.Text = bluetoothAdapter.Name;

    }

    protected override void OnResume()
    {
        base.OnResume();
        //RegisterReceiver(bluetooth, new IntentFilter(""));
    }

    protected override void OnPause()
    {
        base.OnPause();
        //UnregisterReceiver(bluetooth);
    }

    void DeviceListClick (object sender, AdapterView.ItemClickEventArgs args)
    {
        // Cancel discovery because it's costly and we're about to connect
        bluetoothAdapter.CancelDiscovery();

        //Get the device MAC address, which is the last 17 chars in the View
        var info = (args.View as TextView).Text.ToString();
        var address = info.Substring(info.Length - 17);

        //Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.PutExtra(Extra_Device_Address, address);

        //Set result and finish this Activity
        SetResult(Result.Ok, intent);
        Finish();
    }

    private void DoDiscovery()
    {
        //Indicate scanning in the title
        SetProgressBarIndeterminateVisibility(true);
        SetTitle(Resource.String.scanning);

        //Turn on sub-title for new devices
        FindViewById<View>(Resource.Id.NewDevice).Visibility = ViewStates.Visible;

        //If we're already discovering, stop it
        if (bluetoothAdapter.IsDiscovering)
        {
            bluetoothAdapter.CancelDiscovery();
        }

        //Request disccover from BluetoothAdapter
        bluetoothAdapter.StartDiscovery();
    }

    public class Receiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;

            // When discovery finds a device
            if (action == BluetoothDevice.ActionFound)
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                // If it's already paired, skip it, because it's been listed already
                if(device.BondState != Bond.Bonded)
                {
                    Device.Add(device.Name + "\n" + device.Address);
                }
                // When discovery is finished, change the Activity title
                else if(Device.Count == 0)
                {
                    Device.Add("Empty");
                }
            }
        }
    }
  }
}

Testing my code, I found out that my application is unable to detect Bluetooth devices and also it is unable to display them. I went online to find examples to follow and did not find anything wrong. Any helps would be greatly appreciated. Apologies if I made small mistakes, this is my first time trying to create android application using Xamarin.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • 1
    Do you have [all the necessary permissions](https://developer.android.com/guide/topics/connectivity/bluetooth.html) ? – orhtej2 Dec 26 '17 at 22:46
  • By `Device = new ArrayAdapter(this, Resource.Layout.Main);`, it is your code in your application? or it is just a simple you want to show your question. If it is your real code, you need replace the `Resource.Layout.Main` with a layout which only a `TextView` in it. – Robbit Dec 27 '17 at 01:28
  • Yes, it is my main code inside. Why do I need to replace it with Resource.Layout.Main, I don't really understand could you further explain? – ng kian yong Dec 27 '17 at 04:53
  • [Because it is necessary for your ArrayAdapter ](https://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context, int) ), and I got error when I try your code. [Take a look this](https://stackoverflow.com/questions/9280965/arrayadapter-requires-the-resource-id-to-be-a-textview-xml-problems) – Robbit Dec 27 '17 at 06:04
  • Please create a new layout whatever you want to name it, and just put a `TextView` in the layout like the last link I provided for you, and try a again. – Robbit Dec 27 '17 at 06:07
  • I have changed like you told me too. However, I am currently still unable to detect any Bluetooth devices near me which in turn does not let me see if it works. I do not know what is wrong with my code. I have also added the required permission on Android.Manifest file. – ng kian yong Dec 27 '17 at 10:51
  • Does there any errors after changing your codes? – Robbit Jan 02 '18 at 05:46
  • I have found [this demo](https://github.com/conceptdev/xamarin-forms-samples/tree/master/BluetoothTISensor) for you. – Robbit Jan 02 '18 at 08:33

0 Answers0