capacitor-pozo-printer/android/src/main/java/com/pozo/printer/UsbPrinter.java

90 lines
2.8 KiB
Java
Raw Normal View History

2026-03-18 09:43:44 +05:30
package com.pozo.printer;
import android.content.Context;
import android.hardware.usb.*;
import com.getcapacitor.JSObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class UsbPrinter {
public static List<JSObject> scanDevices(Context context) {
List<JSObject> result = new ArrayList<>();
UsbManager manager =
(UsbManager) context.getSystemService(Context.USB_SERVICE);
if (manager == null) return result;
HashMap<String, UsbDevice> devices = manager.getDeviceList();
for (UsbDevice device : devices.values()) {
JSObject obj = new JSObject();
obj.put(
"name",
device.getProductName() != null ? device.getProductName() : "USB Device"
);
obj.put("address", String.valueOf(device.getDeviceId()));
result.add(obj);
}
return result;
}
public static void print(
Context context,
byte[] data,
String deviceIdStr
) throws Exception {
UsbManager manager =
(UsbManager) context.getSystemService(Context.USB_SERVICE);
if (manager == null) throw new Exception("USB service not available");
HashMap<String, UsbDevice> devices = manager.getDeviceList();
UsbDevice targetDevice = null;
if (deviceIdStr != null) {
int deviceId = Integer.parseInt(deviceIdStr);
for (UsbDevice device : devices.values()) {
if (device.getDeviceId() == deviceId) {
targetDevice = device;
break;
}
}
} else {
if (!devices.isEmpty()) {
targetDevice = devices.values().iterator().next();
}
}
if (targetDevice == null) throw new Exception("USB printer not found");
if (!manager.hasPermission(targetDevice))
throw new Exception("USB permission denied — prompt user first");
UsbInterface intf = targetDevice.getInterface(0);
UsbEndpoint endpoint = null;
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
endpoint = ep;
break;
}
}
if (endpoint == null) throw new Exception("No OUT endpoint on USB device");
UsbDeviceConnection connection = manager.openDevice(targetDevice);
if (connection == null) throw new Exception("Cannot open USB device");
connection.claimInterface(intf, true);
try {
int chunkSize = endpoint.getMaxPacketSize();
int offset = 0;
while (offset < data.length) {
int size = Math.min(chunkSize, data.length - offset);
byte[] chunk = new byte[size];
System.arraycopy(data, offset, chunk, 0, size);
connection.bulkTransfer(endpoint, chunk, size, 5000);
offset += size;
}
} finally {
connection.releaseInterface(intf);
connection.close();
}
}
}