Android USB принтер Otg - PullRequest
       39

Android USB принтер Otg

0 голосов
/ 27 мая 2018

Я пытаюсь распечатать на USB-принтере Zebra, используя следующий код

В соответствии с документацией UsbDeviceConnection#bulkTransfer - это значение длины, указанной в документации ...@return length of data transferred (or zero) for success,or negative value for failure

Мой код указан ниже

package in.silentsudo.andoidprinter.usbprinter;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

import in.silentsudo.andoidprinter.R;

public class MainActivity extends Activity {

    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;
    private PendingIntent mPermissionIntent;
    private UsbDeviceConnection usbConnection;
    UsbEndpoint usbWriterEndpoint;
    UsbInterface usbInterface;

    private static final String ACTION_USB_PERMISSION = "in.silentsudo.usbprinter.USB_PERMISSION";

    private StringBuffer logBuffer = new StringBuffer();

    private TextView textView;
    private Button button;

    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.txt_status);
        button = findViewById(R.id.btn_print);
        addLog("Creating usbConnection");
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        String usbManagerString = mUsbManager == null ? "USBManager is null" : "USB manager is valid";
        addLog(usbManagerString);
    }


    @Override
    protected void onResume() {
        super.onResume();
        mPermissionIntent = PendingIntent.getBroadcast(this,
                0,
                new Intent(ACTION_USB_PERMISSION),
                0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filter);
        addLog("Registered received with filter :" + ACTION_USB_PERMISSION);
        if (mUsbManager != null) {
            if (mUsbManager.getDeviceList() != null && mUsbManager.getDeviceList().size() > 0) {
                addLog("Total usb devices: " + mUsbManager.getDeviceList().size());
                for (Map.Entry<String, UsbDevice> entry : mUsbManager.getDeviceList().entrySet()) {
                    addLog("\t" + entry.getKey() + " -> " + entry.getValue().getSerialNumber());
                    mUsbDevice = entry.getValue();
                }
            } else {
                addLog("No device connected");
            }
        }
        addLog("Waiting for usbConnection");
        addLog("Setting up interfaces");
        setUpInterfaces();
    }


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mUsbReceiver);
        if (usbConnection != null) {
            usbConnection.releaseInterface(usbInterface);
        }
    }

    public void setUpInterfaces() {
        if (mUsbDevice != null) {
            int interfaceCount = mUsbDevice.getInterfaceCount();
            addLog("\b" + mUsbDevice.getSerialNumber() + " has total " + interfaceCount + "Interface count");
            for (int i = 0; i < interfaceCount; i++) {
                final UsbInterface usbInterface = mUsbDevice.getInterface(i);
                addLog("\t\tusb at index " + i + " " + getInterfaceDataAsString(usbInterface));
                final int endpointCount = usbInterface.getEndpointCount();
                addLog("\t\t\t " + usbInterface.getId() + " has total " + endpointCount + " endpoints");
                UsbEndpoint point0 = usbInterface.getEndpoint(0);
                UsbEndpoint point1 = usbInterface.getEndpoint(1);
                printUsbEndPointAsString(point0);
                printUsbEndPointAsString(point1);
                usbWriterEndpoint = point1;
                this.usbInterface = usbInterface;
            }

        }

    }

    final String THREAD_TAG = "BG THREAD:-> ";

    public boolean connectAndClaim() {
        usbConnection = mUsbManager.openDevice(mUsbDevice);
        if (usbConnection != null) {
            Log.e("Connection:", " connected");
            addLog("Device connected");
        }
        return usbConnection.claimInterface(usbInterface, true);
    }


    public void writeToPrinter(final String contentToBeWritten) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    addLog(THREAD_TAG + "Writing to usbConnection");
                    addLog(THREAD_TAG + " Content to be written `" + contentToBeWritten + "`");
                    addLog(THREAD_TAG + " Content size`" + contentToBeWritten.length() + "`");
                    byte[] bytes = contentToBeWritten.getBytes();
                    int b = usbConnection.bulkTransfer(usbWriterEndpoint, bytes, bytes.length, 50000);

                    addLog(THREAD_TAG + "Written status " + b);
                    addLog(THREAD_TAG + "Written to usbConnection");
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    String exceptionAsString = sw.toString();
                    addLog(THREAD_TAG + exceptionAsString);
                }
            }
        });
        thread.start();
    }

    private void printUsbEndPointAsString(UsbEndpoint point) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(point.toString());
        stringBuilder.append(", type" + point.getType());
        stringBuilder.append(", direction" + point.getDirection());
        addLog(stringBuilder.toString());
    }

    private String getInterfaceDataAsString(UsbInterface usbInterface) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("id = " + usbInterface.getId());
        stringBuilder.append(", iClass = " + usbInterface.getInterfaceClass());
        stringBuilder.append(", protocol = " + usbInterface.getInterfaceProtocol());
        stringBuilder.append(", priSubClassotocol = " + usbInterface.getInterfaceSubclass());
        return stringBuilder.toString();
    }

    public void print(View view) {
        String msg = "demo";
        if (connectAndClaim()) {
            addLog("Claim successful writing to printer");
            writeToPrinter(msg);
        } else {
            addLog("Claim failure");
        }
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            addLog("ACTION RECEIVED in USB RECEIVER : " + action);
            if (ACTION_USB_PERMISSION.equals(action)) {
                addLog("action if");
                synchronized (this) {
                    mUsbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (mUsbDevice != null) {
                            //call method to set up device communication
                            addLog("Device received from BROADCAST RECEIVER");
                        }
                    } else {
                        addLog("permission denied for device " + mUsbDevice.getSerialNumber());
                    }
                }
            } else {
                addLog("action else");
            }
        }
    };


    private void addLog(final String msg) {
        logBuffer.append(msg);
        logBuffer.append("\n");
        textView.post(new Runnable() {
            @Override
            public void run() {
                textView.append(msg);
                textView.append("\n");
            }
        });
    }
}

Я не вижу никаких журналов ошибок или ошибок. Последнее сообщение потока также успешно записывается, но содержимое не записывается на принтер.Есть ли что-то, что я делаю неправильно, пожалуйста, проверьте.

1 Ответ

0 голосов
/ 12 июня 2018

Я думаю, что ваша setUpInterfaces() функция неверна.Это не способ проходить через конечные точки и устанавливать входные и выходные конечные точки.Это делается так:

for(i in 0..(usbDevice!!.interfaceCount - 1)){
        val usbInterfac = usbDevice!!.getInterface(i)
        if(usbInterfac.interfaceClass == UsbConstants.USB_CLASS_CDC_DATA) {
            var tout: UsbEndpoint? = null
            var tin: UsbEndpoint? = null
            val endpointCount = usbInterfac.endpointCount
            if (endpointCount >= 2) {
                for (j in 0..(endpointCount - 1)) {
                    if (usbInterfac.getEndpoint(j).type == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                        if (usbInterfac.getEndpoint(j).direction == UsbConstants.USB_DIR_OUT) {
                            tout = usbInterfac.getEndpoint(j)
                        } else if (usbInterfac.getEndpoint(j).direction == UsbConstants.USB_DIR_IN) {
                            tin = usbInterfac.getEndpoint(j)
                        }
                    }
                }

                if (tout != null && tin != null) {
                    usbInterface = usbInterfac
                    endpointOut = tout
                    endpointIn = tin
                }
            }
        }
}

Вы неправильно устанавливаете конечную точку вывода, и, следовательно, принтер не получает ваши данные.(Пожалуйста, не возражайте, решение на языке котлина)

...