2017-09-04 1 views
15

저는이 문제에 대한 해결책을 찾고자했지만 그럴 수 없었습니다. 그래서 안드로이드에서 POS 애플 리케이션을 개발하고 블루투스 프린터를 사용하여 판매/구매 영수증을 인쇄해야합니다.mBluetoothSocket.connect()는 줄을 인쇄합니다.

인쇄, 자체, 잘 작동,하지만 난 mBluetoothSocket.connect()를 호출 할 때마다, 내가하지 않는, 인쇄의 상단에 CONNECT "8869-XX-XXXXXX"을 출력 필요. 나는 오랫동안 연결을 열어두고 싶지 않고 필요한 때에 만 앱을 연결하기를 원합니다. 이것을 달성하는 방법? 도움 사람. 아래 코드를 찾으십시오. 미리 감사드립니다.

package anil.com.andoirdbluetoothprint; 


import java.io.IOException; 
import java.io.OutputStream; 
import java.nio.ByteBuffer; 
import java.util.Set; 
import java.util.UUID; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.Toast; 


public class MainActivity extends Activity implements Runnable { 
    protected static final String TAG = "TAG"; 
    private static final int REQUEST_CONNECT_DEVICE = 1; 
    private static final int REQUEST_ENABLE_BT = 2; 
    Button mScan, mPrint, mDisc; 
    BluetoothAdapter mBluetoothAdapter; 
    private UUID applicationUUID = UUID 
      .fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    private ProgressDialog mBluetoothConnectProgressDialog; 
    private BluetoothSocket mBluetoothSocket; 
    BluetoothDevice mBluetoothDevice; 

    @Override 
    public void onCreate(Bundle mSavedInstanceState) { 
     super.onCreate(mSavedInstanceState); 
     setContentView(R.layout.activity_main); 
     mScan = (Button) findViewById(R.id.Scan); 
     mScan.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View mView) { 
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
       if (mBluetoothAdapter == null) { 
        Toast.makeText(MainActivity.this, "Message1", Toast.LENGTH_SHORT).show(); 
       } else { 
        if (!mBluetoothAdapter.isEnabled()) { 
         Intent enableBtIntent = new Intent(
           BluetoothAdapter.ACTION_REQUEST_ENABLE); 
         startActivityForResult(enableBtIntent, 
           REQUEST_ENABLE_BT); 
        } else { 
         ListPairedDevices(); 
         Intent connectIntent = new Intent(MainActivity.this, 
           DeviceListActivity.class); 
         startActivityForResult(connectIntent, 
           REQUEST_CONNECT_DEVICE); 
        } 
       } 
      } 
     }); 

     mPrint = (Button) findViewById(R.id.mPrint); 
     mPrint.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View mView) { 
       Thread t = new Thread() { 
        public void run() { 
         try { 
          OutputStream os = mBluetoothSocket 
            .getOutputStream(); 
          String BILL = ""; 
// Before this line, it is printing "CONNECT 88C9-XX-XXXXXX" 
          BILL = "Company Name \n"; 
          BILL = BILL + "Address \n"; 
          BILL = BILL + "--------------- \n"; 
          BILL = BILL + "Item1 : Quantity \n"; 
          BILL = BILL + "Rate : 100 $ \n"; 
          BILL = BILL + "-----------------\n"; 
          BILL = BILL + "Thank You \n"; 
          os.write(BILL.getBytes()); 
          //This is printer specific code you can comment ==== > Start 

          // Setting height 
          int gs = 29; 
          os.write(intToByteArray(gs)); 
          int h = 104; 
          os.write(intToByteArray(h)); 
          int n = 162; 
          os.write(intToByteArray(n)); 

          // Setting Width 
          int gs_width = 29; 
          os.write(intToByteArray(gs_width)); 
          int w = 119; 
          os.write(intToByteArray(w)); 
          int n_width = 2; 
          os.write(intToByteArray(n_width)); 


         } catch (Exception e) { 
          Log.e("MainActivity", "Exe ", e); 
         } 
        } 
       }; 
       t.start(); 
      } 
     }); 

     mDisc = (Button) findViewById(R.id.dis); 
     mDisc.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View mView) { 
       if (mBluetoothAdapter != null) 
        mBluetoothAdapter.disable(); 
      } 
     }); 

    }// onCreate 

    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     try { 
      if (mBluetoothSocket != null) 
       mBluetoothSocket.close(); 
     } catch (Exception e) { 
      Log.e("Tag", "Exe ", e); 
     } 
    } 

    @Override 
    public void onBackPressed() { 
     try { 
      if (mBluetoothSocket != null) 
       mBluetoothSocket.close(); 
     } catch (Exception e) { 
      Log.e("Tag", "Exe ", e); 
     } 
     setResult(RESULT_CANCELED); 
     finish(); 
    } 

    public void onActivityResult(int mRequestCode, int mResultCode, 
           Intent mDataIntent) { 
     super.onActivityResult(mRequestCode, mResultCode, mDataIntent); 

     switch (mRequestCode) { 
      case REQUEST_CONNECT_DEVICE: 
       if (mResultCode == Activity.RESULT_OK) { 
        Bundle mExtra = mDataIntent.getExtras(); 
        String mDeviceAddress = mExtra.getString("DeviceAddress"); 
        Log.v(TAG, "Coming incoming address " + mDeviceAddress); 
        mBluetoothDevice = mBluetoothAdapter 
          .getRemoteDevice(mDeviceAddress); 
        mBluetoothConnectProgressDialog = ProgressDialog.show(this, 
          "Connecting...", mBluetoothDevice.getName() + " : " 
            + mBluetoothDevice.getAddress(), true, false); 
        Thread mBlutoothConnectThread = new Thread(this); 
        mBlutoothConnectThread.start(); 
        // pairToDevice(mBluetoothDevice); This method is replaced by 
        // progress dialog with thread 
       } 
       break; 

      case REQUEST_ENABLE_BT: 
       if (mResultCode == Activity.RESULT_OK) { 
        ListPairedDevices(); 
        Intent connectIntent = new Intent(MainActivity.this, 
          DeviceListActivity.class); 
        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE); 
       } else { 
        Toast.makeText(MainActivity.this, "Message", Toast.LENGTH_SHORT).show(); 
       } 
       break; 
     } 
    } 

    private void ListPairedDevices() { 
     Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter 
       .getBondedDevices(); 
     if (mPairedDevices.size() > 0) { 
      for (BluetoothDevice mDevice : mPairedDevices) { 
       Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " 
         + mDevice.getAddress()); 
      } 
     } 
    } 

    public void run() { 
     try { 
      mBluetoothSocket = mBluetoothDevice 
        .createRfcommSocketToServiceRecord(applicationUUID); 
      mBluetoothAdapter.cancelDiscovery(); 
      mBluetoothSocket.connect(); 
      mHandler.sendEmptyMessage(0); 
     } catch (IOException eConnectException) { 
      Log.d(TAG, "CouldNotConnectToSocket", eConnectException); 
      closeSocket(mBluetoothSocket); 
      return; 
     } 
    } 

    private void closeSocket(BluetoothSocket nOpenSocket) { 
     try { 
      nOpenSocket.close(); 
      Log.d(TAG, "SocketClosed"); 
     } catch (IOException ex) { 
      Log.d(TAG, "CouldNotCloseSocket"); 
     } 
    } 

    private Handler mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      mBluetoothConnectProgressDialog.dismiss(); 
      Toast.makeText(MainActivity.this, "DeviceConnected", Toast.LENGTH_SHORT).show(); 
     } 
    }; 

    public static byte intToByteArray(int value) { 
     byte[] b = ByteBuffer.allocate(4).putInt(value).array(); 

     for (int k = 0; k < b.length; k++) { 
      System.out.println("Selva [" + k + "] = " + "0x" 
        + UnicodeFormatter.byteToHex(b[k])); 
     } 

     return b[3]; 
    } 

    public byte[] sel(int val) { 
     ByteBuffer buffer = ByteBuffer.allocate(2); 
     buffer.putInt(val); 
     buffer.flip(); 
     return buffer.array(); 
    } 

} 

답변

3

이것은이 행을 인쇄하는 코드는 아니지만 사용자가 작성한 잘못된 프린터 구성입니다. . . 모든 프린터는 그들의 구성 및 설정하지만 거의 POS 프린터의 대부분 (귀하의 경우) 페이지 여백, HEADER를 구성하는 것을 제안, 바닥 글과 공백에 인쇄 prefrences으로 this 확인 당신이 두 가지 선택

1로 남아 있도록해야 - > 구성/설정 환경 설정 (이것은 실제 데이터를 전송하기 전에 프린터로 전송하는 당신은 프린터 명령의 지식이 있어야합니다)

마지막으로 적어도 그것을 인쇄하기 전에 - 수동> 중 하나를 설정 환경 설정

이 (가 편리합니다) 귀하의 POS 프린터와 안드로이드 장치가 함께 친숙하지 않을 수도 있습니다 : D. . 인쇄용 데이터에 성공한 손익 코드/응답을 상호 프린터로 인코딩 한 통신 코드가 일치하지 않을 수 있습니다.

프린터를 사용하지 않도록 설정하거나 프린터가 좋아하는 코드/응답을 보내야합니다. .