使用xamarin.forms通过蓝牙打印机打印数据

时间:2017-10-18 04:55:42

标签: android xamarin xamarin.forms xamarin.android bluetooth-printing

我正在做一个跨平台的应用程序,我需要通过蓝牙打印机打印一组数据。因为我已经通过互联网找到了一种从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连接成功”。但我无法从打印机打印数据。我使用的是星型微米级打印机,型号为“TSP 100 III BI”。

如果我遗失任何东西,任何人都可以建议我。

这对我来说是一个很大的帮助。谢谢。

1 个答案:

答案 0 :(得分:-2)

代码看起来不错。但是,如果发送给它的数据很小,打印机有时不会打印。尝试在多行中发送更多数据以进行样本打印:

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