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

标签 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 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/

相关文章:

java - 如何计算字符串中格式字符的数量?

android - 停止 Astro Manager 进行备份

android - 带有圆角的 ImageView 通过另一个图像作为背景

azure - 使用自定义设置配置 Azure b2C 身份验证

没有 Xamarin.Forms 的 Xamarin BeginInvokeOnMainThread

android - 我可以在 Windows 中将我的 Android Studio 版本从 2.3.3 升级到 3.0 吗?

c# - 在monodroid webview中加载带有pdf的url

c# - 正确中止或取消 PostAsync

c# - RestSharp android 上传多行

android - Xamarin.Forms 滑动手势识别器