2015-03-19 162 views
0

我們有一個原生的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

回答

0

我找到了解決我的問題的方法。這是一種解決方法,但無論如何它都能正常工作。我添加一個Thread.sleep(100);在mmOutputStream = mmSocket.getOutputStream();之後線。之後,它工作正常。我不知道爲什麼,但它現在起作用。