android 设备是可以连接打印机的.
而且系统版本越高,API越是完善.
我的设备是4.x的平板设备.
发现打印设备的代码:
//重要的是获取到UsbManager 这个是发现打印设备的方法
UsbDevice usbDevice = null;
UsbManager usbManager = (UsbManager) Application.getInstance().getSystemService(Service.USB_SERVICE);
HashMap<String, UsbDevice> deviceMap = usbManager.getDeviceList();
if (deviceMap.isEmpty()) {
if (BuildConfig.DEBUG) return;
return;
}
Iterator<String> deviceIterator = deviceMap.keySet().iterator();
while (deviceIterator.hasNext()) {
/**
*device.getInterface(0).getInterfaceClass() == 7是打印机
*/
UsbDevice device = deviceMap.get(deviceIterator.next());
if (device.getDeviceClass() == 0 && device.getInterface(0).getInterfaceClass() == 7) {
//这里拿到自己的打印设备 拿到设备之后可以获取到这个设备的重要信息 vid和pid
usbDevice = device;
//每个usb设备都有唯一的 Vid 和 Pid 就是厂商id 和 产品id
//当知道了设备的vid,pid之后就可以很简单的做一个安卓设备连接多个打印机了
if (1155 == device.getVendorId() && 208 == getProductId()) { //这个是已知的设备vid,pid
//可以在这里根据需要赋值给usbDevice
} else if (2655 == device.getVendorId() && 1122 == getProductId()) {//这是另一个打印机的vid,pid
//可以在这里根据需要赋值给usbDevice
//设备可以同时连接一台,根据需要切换 相当于多台. 我项目里需要一个打印快递单,一个打印小票,就需要切换打印机
//解决方案是写了两个打印类,分别对应两个SP文件,可以手动保存打印机的用途到Sp文件,然后对比打印机的vid,pid是否在文件
//列表,在进行打印,好处就是可以扩展未知打印机实现各司其职的打印
}
}
//获取权限 通过全局的context获取UsbManager
UsbManager usbManager = (UsbManager) Application.getInstance().getSystemService(Service.USB_SERVICE);
if (usbManager.hasPermission(usbDevice)) {
//尝试连接打印设备
openDevice();
} else {
PendingIntent pendingIntent = PendingIntent.getBroadcast(Application.getInstance(), 0, new Intent(
"项目的包名.USB"), 0);
Application.getInstance().registerReceiver(permissionReceiver,
new IntentFilter("项目包名.USB"));
usbManager.requestPermission(usbDevice, pendingIntent);
}
}
//尝试连接打印设备的方法
public void openDevice() {
UsbManager usbManager = (UsbManager) Application.getInstance().getSystemService(Service.USB_SERVICE);
usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
ToastUtil.showShort("连接打印机失败");
return;
}
if (usbDeviceConnection.claimInterface(usbDevice.getInterface(0), true)) {
ToastUtil.showShort("连接打印机成功");
} else {
ToastUtil.showShort("连接打印机失败");
usbDeviceConnection.close();
usbDeviceConnection = null;
}
}
//调用UsbDeviceConnection的bulkTransfer方法进行打印
usbDeviceConnection.bulkTransfer();
//释放资源
public void onDestroy() {
if (usbDeviceConnection != null) {
usbDeviceConnection.close();
usbDeviceConnection = null;
}
if (usbDevice != null) {
usbDevice = null;
}
if (usbEndOut != null) {
usbEndOut = null;
}
}
package android.hardware.usb;
public class UsbDeviceConnection {
.........
/**
* Performs a bulk transaction on the given endpoint.
* The direction of the transfer is determined by the direction of the endpoint.
* <p>
* This method transfers data starting from index 0 in the buffer.
* To specify a different offset, use
* {@link #bulkTransfer(UsbEndpoint, byte[], int, int, int)}.
* </p>
*
* @param endpoint the endpoint for this transaction
* @param buffer buffer for data to send or receive
* @param length the length of the data to send or receive
* @param timeout in milliseconds
* @return length of data transferred (or zero) for success,
* or negative value for failure
*/
public int bulkTransfer(UsbEndpoint endpoint,
byte[] buffer, int length, int timeout) {
return bulkTransfer(endpoint, buffer, 0, length, timeout);
}
..........
}
///////////////////一个可用的Print类///////////////////////////
public class Print {
private UsbDevice usbDevice;
private UsbDeviceConnection usbDeviceConnection;
private UsbEndpoint usbEndOut;
private UsbEndpoint usbEndIn;
private Print() {
}
static class ArgoxPrintHolder {
static Print INSTANCE = new Print();
}
public static Print getInstance() {
return ArgoxPrintHolder.INSTANCE;
}
public void onStart(boolean b) {
UsbManager usbManager = (UsbManager) Application.getInstance().getSystemService(Service.USB_SERVICE);
HashMap<String, UsbDevice> deviceMap = usbManager.getDeviceList();
if (deviceMap.isEmpty()) {
return;
}
Iterator<String> deviceIterator = deviceMap.keySet().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceMap.get(deviceIterator.next());
/**
*device.getInterface(0).getInterfaceClass() == 7是打印机
*/
if (device.getDeviceClass() == 0 && device.getInterface(0) != null && device.getInterface(0).getInterfaceClass() == 7) {
if (b)
usbDevice = device;
else
usbDevice = null;
}
}
if (usbDevice == null) {
return;
}
UsbInterface usbInterface = usbDevice.getInterface(0);
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint ep = usbInterface.getEndpoint(i);
switch (ep.getType()) {
case UsbConstants.USB_ENDPOINT_XFER_BULK://块
if (UsbConstants.USB_DIR_OUT == ep.getDirection()) {//输出
usbEndOut = ep;
} else {
usbEndIn = ep;
}
break;
case UsbConstants.USB_ENDPOINT_XFER_CONTROL://控制
break;
case UsbConstants.USB_ENDPOINT_XFER_INT://中断
break;
default:
break;
}
}
checkPermission();
}
public void checkPermission() {
UsbManager usbManager = (UsbManager) YiApplication.getInstance().getSystemService(Service.USB_SERVICE);
if (usbManager.hasPermission(usbDevice)) {
openDevice();
} else {
PendingIntent pendingIntent = PendingIntent.getBroadcast(YiApplication.getInstance(), 0, new Intent(
"包名.USB"), 0);
Application.getInstance().registerReceiver(permissionReceiver,
new IntentFilter("包名.USB"));
usbManager.requestPermission(usbDevice, pendingIntent);
}
}
public void openDevice() {
UsbManager usbManager = (UsbManager) Application.getInstance().getSystemService(Service.USB_SERVICE);
usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
ToastUtil.showShort("连接打印机失败");
return;
}
if (usbDeviceConnection.claimInterface(usbDevice.getInterface(0), true)) {
// ToastUtil.showShort("连接打印机成功");
} else {
ToastUtil.showShort("连接打印机失败");
usbDeviceConnection.close();
usbDeviceConnection = null;
}
}
public void onDestroy() {
if (usbDeviceConnection != null) {
usbDeviceConnection.close();
usbDeviceConnection = null;
}
if (usbDevice != null) {
usbDevice = null;
}
if (usbEndOut != null) {
usbEndOut = null;
}
}
//
@TargetApi(18)
public boolean sendDataPrint(byte[] buffer) {
if (buffer == null || buffer.length == 0) {
return false;
}
if (usbDevice == null) {
onStart(true);
return false;
}
if (usbDeviceConnection == null) {
checkPermission();
return false;
}
boolean success = false;
if (buffer.length > 8000) {
int pos = 0;
while (pos <= buffer.length) {
if ((pos + 8000) < buffer.length) {
success = usbDeviceConnection.bulkTransfer(usbEndOut, buffer, pos, 8000, 500) > 0 ? true : false;
} else {
success = usbDeviceConnection.bulkTransfer(usbEndOut, buffer, pos, buffer.length - pos, 500) > 0 ? true : false;
}
if (!success) break;
pos = pos + 8000;
}
} else {
success = usbDeviceConnection.bulkTransfer(usbEndOut, buffer, buffer.length, 500) > 0 ? true : false;
}
if (!success) { //如果打印失败 直接重置打印机
onDestroy();
onStart(true);
}
return success;
}
private BroadcastReceiver permissionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if ((intent.getAction().equals("包名.USB")) &&
(intent.getBooleanExtra("permission", false))) {
openDevice();
}
}
};
}
///////使用
Print.getInstance().sendDataPrint(s.getBytes());