Android USB打印/蓝牙打印 ESC/POS打印 无依赖其他SDK
USB工具类
新建文件 UsbUtil.java
//USB工具类
public class UsbUtil{
private static UsbManager mUsbManager;
public UsbManager getUsbManager(){
return mUsbManager;
}
private static final String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";
//注册广播
private static final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//广播方法
String action = intent.getAction();
//申请使用USB设备权限回调广播
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
} else {
Toast.makeText(context, "设备的权限被拒绝 " + usbDevice, Toast.LENGTH_SHORT).show();
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
}
}
};
//获取USB设备
public static List<UsbDevice> getUsbDeviceList(Context context) {
//获取USB管理器
mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
//注册申请使用USB设备权限回调广播
context.registerReceiver(mUsbDeviceReceiver, filter);
// 列出所有的USB设备,并且都请求获取USB权限
assert mUsbManager != null;
HashMap<String,UsbDevice> deviceList = mUsbManager.getDeviceList();
int index = 0;
ArrayList<UsbDevice> usbDeviceList = new ArrayList<>();
for (UsbDevice device : deviceList.values()) {
if(!mUsbManager.hasPermission(device)){
//申请使用权限
mUsbManager.requestPermission(device, pendingIntent);
}
usbDeviceList.add(device);
}
return usbDeviceList;
}
public static UsbInterface getUsbInterface(UsbDevice device){
UsbInterface usbInterface = null;
for (int i=0;i<device.getInterfaceCount();i++){
usbInterface = device.getInterface(i);
if (usbInterface.getInterfaceClass() != UsbConstants.USB_CLASS_PRINTER) {
usbInterface = null;
}else{
break;
}
}
return usbInterface;
}
//选择打印机
public static UsbEndpoint getUsbEndpoint(UsbInterface usbInterface) {
UsbEndpoint usbEndpoint = null;
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint ep = usbInterface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
usbEndpoint = ep;
break;
} else {
//这里是输入设备 暂时不管
}
}
}
return usbEndpoint;
}
//打印
public static Boolean print( UsbDevice usbDevice,byte[] bytes){
UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);
UsbInterface usbInterface = getUsbInterface(usbDevice);
UsbEndpoint usbEndpoint = getUsbEndpoint(usbInterface);
if (connection != null && connection.claimInterface(usbInterface, true)) {
int result = connection.bulkTransfer(usbEndpoint