我正在做一个跨平台应用程序,我需要通过蓝牙打印机打印一组数据。为此,我通过互联网找到了一种从 android 打印的方法。这是我实现的代码:
mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
if (mBluetoothAdapter == null)
{
await MyFavHelper.InformUser("No bluetooth adapter found", "Bluetooth");
return;
}
else
{
await MyFavHelper.InformUser("Bluetooth found", "Success");
}
if (!mBluetoothAdapter.IsEnabled)
{
mBluetoothAdapter.Enable();
}
else
{
await MyFavHelper.InformUser("Bluetooth Enabled", "Success");
}
ICollection<BluetoothDevice> pairedDevices = mBluetoothAdapter.BondedDevices;
if (pairedDevices.Count > 0)
{
foreach (BluetoothDevice device in pairedDevices)
{
if (device.Name.Contains("TSP"))
{
mmDevice = device;
break;
}
}
}
else
{
await MyFavHelper.InformUser("Paired Devices not found", "Bluetooth");
return;
}
ParcelUuid uuid = mmDevice.GetUuids().ElementAt(0);
if (mmDevice == null)
{
await MyFavHelper.InformUser("No Device Found", "Sorry");
}
mmsSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);
mmsSocket.Connect();
if (mmsSocket.IsConnected)
{
await MyFavHelper.InformUser("Socket Connected Successfully", "Success");
}
else
{
await MyFavHelper.InformUser("Socket Not Connected Successfully", "Sorry");
}
var datastream = mmsSocket.OutputStream;
byte[] byteArray = Encoding.ASCII.GetBytes("Sample Text");
datastream.Write(byteArray, 0, byteArray.Length);
我成功连接到“Socket connected successfully”。但是我无法从打印机打印数据。我使用的是型号为“TSP 100 III BI”的 star micronics 打印机。
如果我遗漏了什么,任何人都可以给我一个想法。
这对我很有帮助。在此先感谢您。
最佳答案
代码看起来不错。但是,如果发送给它的数据很小,打印机有时不会打印。尝试在多行中发送更多数据以进行示例打印:
byte[] byteArray = Encoding.ASCII.GetBytes("Xamarin bluetooth\nPrinting text test\nSample Text");
或
byte[] byteArray = Encoding.UTF8.GetBytes("Xamarin bluetooth\nPrinting text test\nSample Text");
更多详情 refer to .
关于android - 使用 xamarin.forms 通过蓝牙打印机打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46803071/