Android上的通用蓝牙打印

时间:2019-01-30 22:43:13

标签: android printing bluetooth android-bluetooth

我正在尝试使用蓝牙打印机(DPP-350)进行打印,但我一周都无法实现。

我阅读了很多示例,教程以及所发现的所有内容。没有办法。

  • 我能够连接到打印机
  • 我可以检索它的名称和地址(MAC)

我知道我的代码不是最好的方法,但是应该可以。

这里是:

public class MainActivity extends AppCompatActivity {

    Button btnPrint;
    TextView lblPrinterName;
    ProgressBar progressBar;
    String TAG = "BLUETOOTH ONLY";
    BluetoothAdapter btAdapter;
    BluetoothDevice btDevice;
    private BluetoothSocket btSocket = null;
    private OutputStream outputStream = null;
    private InputStream inputStream = null;

    Thread thread;

    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine);

        btnPrint = findViewById(R.id.btnPrint);
        lblPrinterName = findViewById(R.id.lblPrinterName);
        progressBar = findViewById(R.id.pgBar);

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        btDevice = btAdapter.getBondedDevices().iterator().next();   // Get first paired device

        btnPrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Click");
                if (findBluetoothDevice()) {
                    try {
                        openBluetoothPrinter();
                        if(btSocket.isConnected()){
                            printData();
                            progressBar.setVisibility(View.GONE);
//                            disconnectBT();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


    }

    boolean findBluetoothDevice(){

        try{

            btAdapter = BluetoothAdapter.getDefaultAdapter();
            if(btAdapter==null){
                lblPrinterName.setText("No Bluetooth Adapter found");
            }
            if(btAdapter.isEnabled()){
                Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBT,0);
            }

            Set<BluetoothDevice> pairedDevice = btAdapter.getBondedDevices();

            if(pairedDevice.size()>0){
                for(BluetoothDevice pairedDev:pairedDevice){

                    // My Bluetoth printer name is BTP_F09F1A
                    if(pairedDev.getName().equals("DPP-350")){
                        btDevice=pairedDev;
                        lblPrinterName.setText("Bluetooth Printer Attached: "+pairedDev.getName());
                        Log.d(TAG, "findBluetoothDevice: " + pairedDev.getName() + "  " + pairedDev.getAddress());
//                        break;
                        return true;
                    }
                }
            } else {
                lblPrinterName.setText("Bluetooth Printer Attached");
                return false;
            }


        }catch(Exception ex){
            ex.printStackTrace();
            return false;
        }
        return false;
    }

    void openBluetoothPrinter() throws IOException {
        try{

            //Standard uuid from string //
            UUID uuidString = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
            btSocket=btDevice.createRfcommSocketToServiceRecord(uuidString);
            btSocket.connect();
            outputStream = btSocket.getOutputStream();
            inputStream = btSocket.getInputStream();
            Log.d(TAG, "openBluetoothPrinter: " + btSocket.isConnected());

            beginListenData();

        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

    void beginListenData(){
        try{

            final Handler handler =new Handler();
            final byte delimiter=10;
            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];

            thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    while (!Thread.currentThread().isInterrupted() && !stopWorker){
                        try{
                            int byteAvailable = inputStream.available();
                            if(byteAvailable>0){
                                byte[] packetByte = new byte[byteAvailable];
                                inputStream.read(packetByte);

                                for(int i=0; i<byteAvailable; i++){
                                    byte b = packetByte[i];
                                    if(b==delimiter){
                                        byte[] encodedByte = new byte[readBufferPosition];
                                        System.arraycopy(
                                                readBuffer,0,
                                                encodedByte,0,
                                                encodedByte.length
                                        );
                                        final String data = new String(encodedByte,"US-ASCII");
                                        readBufferPosition=0;
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                lblPrinterName.setText(data);
                                            }
                                        });
                                    }else{
                                        readBuffer[readBufferPosition++]=b;
                                    }
                                }
                            }
                        }catch(Exception ex){
                            stopWorker=true;
                        }
                    }

                }
            });

            thread.start();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    void printData() throws IOException {
        try {
//            String msg = textBox.getText().toString();
            String msg = "I am printing";
            msg+="\n";
            outputStream.write(msg.getBytes());
            progressBar.setVisibility(View.VISIBLE);
//            lblPrinterName.setText("Printing Text...");
        } catch (Exception ex){
            progressBar.setVisibility(View.GONE);
            ex.printStackTrace();
        }
    }

    // Disconnect Printer //
    void disconnectBT() throws IOException {
        try {
            stopWorker=true;
            outputStream.close();
            inputStream.close();
            btSocket.close();
            lblPrinterName.setText("Printer Disconnected.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

我没有其他要测试的蓝牙打印机。 把我放在路上。

0 个答案:

没有答案