Я работаю над проектом, где мне нужно подключиться к сканеру bluetooth (Motorola CS3070). Мне нужно захватить входной поток и использовать его для заполнения окна списка сканированным штрих-кодом. Я попытался создать безопасный сокет и подключиться к нему, но сокет не подключается. (Устройство включено и сопряжено. Он работает как физическая клавиатура и заполняет отсканированный код, если курсор находится в редактируемом поле). Это мой код:Подключение к Bluetooth-сканеру с Xamarin Android
private static BluetoothAdapter bluetoothAdapter = null;
private const int REQUEST_ENABLE_BT = 2;
public static ParcelUuid UUID;
public static Dictionary<string, string> deviceDictionary = new Dictionary<string, string>();
public static int STATE = 0;
public static BluetoothSocket mySocket;
public static Activity _activity;
private static BluetoothReceiver receiver;
private static BluetoothDevice pairedBTDevice;
public void InitializeBluetooth()
{
// Get local Bluetooth adapter
bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
// If the adapter is null, then Bluetooth is not supported
if (bluetoothAdapter == null)
{
Toast.MakeText(this, "Bluetooth is not available", ToastLength.Long).Show();
Finish();
return;
}
// If bluetooth is not enabled, ask to enable it
if (!bluetoothAdapter.IsEnabled)
{
var enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Get connected devices
var listOfDevices = bluetoothAdapter.BondedDevices;
if (listOfDevices.Count > 0)
{
foreach (var bluetoothDevice in listOfDevices)
{
UUID = bluetoothDevice.GetUuids().ElementAt(0);
if (!deviceDictionary.ContainsKey(bluetoothDevice.Name))
deviceDictionary.Add(bluetoothDevice.Name, bluetoothDevice.Address);
}
}
else
{
connectButton.Text = "Scanner Not connected";
connectButton.Clickable = false;
}
if (bluetoothAdapter.IsEnabled && listOfDevices.Count > 0)
{
if (listOfDevices.ElementAt(0).BondState == Bond.Bonded)
{
pairedBTDevice = listOfDevices.ElementAt(0);
mySocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.Uuid);
var thread = new Thread(BTConnect);
thread.Start();
}
}
}
public static void BTConnect()
{
try
{
mySocket.Connect();
_activity.RunOnUiThread(() => connectButton.Text = " Scanner Connected");
_activity.RunOnUiThread(() => connectButton.Clickable = false);
receiver.loop = true;
var thread = new Thread(BTRead, "BTRead");
thread.Start();
}
catch (Exception e)
{
_activity.RunOnUiThread(() => Toast.MakeText(_activity.ApplicationContext, "Couldn't connect. Is the device on and paired?", ToastLength.Long).Show());
_activity.RunOnUiThread(() => connectButton.Text = "Scanner Not connected");
_activity.RunOnUiThread(() => connectButton.Clickable = true);
receiver.loop = false;
}
}
Код дает исключение на линии mySocket.Connect();
Исключение составляет Java.IO.IOException: "read failed, socket might closed or timeout, read ret: -1"
. Я также попытался создать резервный сокет с некоторым примером, который я нашел on StackOverflow here, но это меня не помогло. Может кто-то, пожалуйста, помогите мне решить это.
Благодаря
Edit * Мое приложение имеет следующие разрешения: блютус
- android.permission.BLUETOOTH_ADMIN
- android.permission.BLUETOOTH
Можем ли мы видеть код, в котором вы создаете свой сокет? – gimpycpu
«BluetoothSocket mySocket» объявлен как член класса, а код для создания сокета существует в методе InitializeBluetooth() 'mySocket = pairedBTDevice.CreateRfcommSocketToServiceRecord (UUID.Uuid);'. Я здесь что-то не так? –