【问题标题】:Android Print from bluetooth only onceAndroid 仅从蓝牙打印一次
【发布时间】:2015-03-19 10:00:04
【问题描述】:

我们有一个原生的安卓应用程序,您可以通过蓝牙打印发票和运单。我使用了默认的蓝牙适配器。当我从应用程序点击打印按钮时,蓝牙打印机打印我发送的内容没有问题,但是当我再次打印时,打印文本已损坏。在文档打印机的一半停止并倒回纸张并打印我发送的文本的左侧。那时我关闭打印机并再次打开。然后我从应用程序按打印。再次打印机在第一次打印时工作正常。但是当我打印第二个副本时,打印机再次失败。我无法理解发生了什么。如果我使用的代码或适配器有问题,我无法打印任何短信,但我只有在第二份副本中有问题。

这是我的代码:

public BluetoothDevice FindPrinter() {
    BluetoothDevice currentDevice = null;

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            throw new Exception("Bluetooth adaptorü bulunamadı");
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Activity a = new Activity();
            a.startActivityForResult(enableBluetooth, 0);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                                 if(device.getName().equals(SharedPreferenceSettings.getPrinterPort(context))) {
                    currentDevice = device;
                }
            }
        }

    } catch (Exception e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    return currentDevice;
}
public void Print() 
{
    try {
        int current = 0;
        FormatData();
        int line = 0;

        Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
        mmSocket.connect();
        while (current < Data.length) {
            mmOutputStream = mmSocket.getOutputStream();
            int len = 256;
            if (current + 256 > Data.length) {
                len = Data.length - current;
            }
            byte[] temp = new byte[len];
            System.arraycopy(Data, current, temp, 0, len);
            int currentLine = CountLines(temp);
            line = line + currentLine;
            mmOutputStream.write(temp);
            current += len;
            Thread.sleep(1700);
        }
        mmOutputStream.close();
        if(mmSocket.isConnected())
            mmSocket.close();
    } catch (Exception e) {
        Log.e("Print ERROR", e.getMessage());
    }

}

编辑:

我注意到了一些东西。如果我使用调试和断点运行我的应用程序,它可以完美运行,但如果我正常运行它,有时打印机会跳过前 256 个字节然后打印。仍然不明白为什么打印机有时会跳过前 256 个字节。

【问题讨论】:

  • 你有没有尝试使用 2 socket instrance 。一个用于第一个文本,第二个用于复制?
  • 必须不需要第二个套接字。因为在每次打印操作后,我都会关闭并处理套接字实例。
  • 你有没有尝试写另一个字节数组长度? int len = 512;

标签: java android printing bluetooth


【解决方案1】:

我找到了解决问题的方法。这是一种解决方法,但无论如何它都有效。我添加了一个 Thread.sleep(100);在 mmOutputStream = mmSocket.getOutputStream() 之后;线。之后它工作正常。我不知道为什么,但它现在可以工作了。

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2013-11-11
    相关资源
    最近更新 更多