Android只能从蓝牙打印一次

问题描述:

我们有一个原生的android应用程序,您可以通过蓝牙从它打印发票。我使用了默认的蓝牙适配器。当我从应用程序打印按钮,蓝牙打印机打印我发送没有问题,但是当我再次打印,打印文本已损坏。在文档打印机的一半处,停止并倒带纸张并打印我发送的文本的左侧。此时,我关闭打印机并重新打开。然后我按从应用程序打印。第一次打印时,打印机再次正常工作。但是当我打印第二个副本时,打印机再次失败。我不明白发生了什么事。如果我使用的代码或适配器有问题,我无法打印任何文本消息,但我只有第二个副本有问题。Android只能从蓝牙打印一次

这里是我的代码:

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个字节。

+0

你有没有尝试使用2插座instrance。第一个文本,第二个复制? – Yahor10 2015-03-19 10:07:46

+0

一定不需要第二个插座。因为在每次打印操作之后,我都关闭并处理套接字实例。 – 2015-03-20 11:16:12

+0

你有没有尝试写另一个字节数组的长度? int len = 512; – Yahor10 2015-03-26 11:09:54

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