Android USB Otg打印机

时间:2018-05-27 06:27:07

标签: android usb zebra-printers printers

我正在尝试使用以下代码打印到usb打印机斑马

根据文档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 :(得分:0)

我认为您的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
                }
            }
        }
}

您正在错误地设置输出端点,因此打印机无法获取您的数据。 (请不要介意,解决方案是Kotlin语言)