KillGeek KillGeek - 1 month ago 11
Android Question

Get nearby bluetooth devices in android c#

I need to make an app that will discover all the nearby Bluetooth devices and connect to it. I have this code that will probably work in Java but I need it to work in C#:

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

// When discovery finds a device
if (BluetoothDevice.ActionFound.Equals(action))
{
BluetoothDevice device = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.Add(device.Name+" -> "+device.Address);
lv.Adapter = mArrayAdapter;
}
}
}


The problem is that Visual Studio says:


Can't implicitly convert Java.Lang.Object to Android.Bluetooth.BluetoothDevice.

Are you missing a cast?


in this line:

BluetoothDevice device = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

Answer

GetParcelableExtra is a general method that can be used to return many things. Instances of BluetoothDevice are only one of the things that it may return.

During compilation, the compiler doesn't know that what comes out of your call to GetPardelableExtra is an instance of BluetoothDevice. It only knows that some object will come out of it. So, apparently in Xamarin for Android, it simply returns a java.lang.Object. Only at runtime is it known that this Object contains an instance of BluetoothDevice.

The solution is provided in the error message; you need to cast the returned value to BluetoothDevice:

Object obj = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
BluetoothDevice device = obj as BluetoothDevice;
if (device != null)
{
    // Rest of your code.
}

If the cast fails, it will return a null, so the null check is important.
If you get that null value, you will probably take some kind of action - mention it in logs or console to help you debug later.