[英]Get nearby bluetooth devices in android c#
我需要制作一個能夠發現所有附近藍牙設備並連接到它的應用程序。 我有這個代碼可能在Java中工作,但我需要它在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;
}
}
}
問題是Visual Studio說:
無法將Java.Lang.Object隱式轉換為Android.Bluetooth.BluetoothDevice。
你錯過了演員嗎?
在這一行:
BluetoothDevice device = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
GetParcelableExtra
是一種可用於返回許多內容的通用方法。 BluetoothDevice
實例只是它可能返回的事情之一。
在編譯期間,編譯器不知道您對GetPardelableExtra
的調用GetPardelableExtra
是BluetoothDevice
的實例。 它只知道會有一些物體出現。 因此,顯然在Android的Xamarin中,它只返回一個java.lang.Object
。 僅在運行時才知道此Object包含BluetoothDevice
的實例。
解決方案在錯誤消息中提供; 你需要將返回的值轉換為BluetoothDevice
:
Object obj = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
BluetoothDevice device = obj as BluetoothDevice;
if (device != null)
{
// Rest of your code.
}
如果轉換失敗,它將返回null
,因此null檢查很重要。
如果你得到那個null
值,你可能會采取某種行動 - 在日志或控制台中提及它以幫助你稍后調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.