一、新建MyUsbPrinterUtil工具类,代码如下:
 
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
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.Build;
import android.util.Log;import com.posin.usbprinter.UsbPrinter;import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;/*** Created by Administrator on 2018/1/5.* 这是小票打印机工具类*/public class MyUsbPrinterUtil {private static final String TAG = "UsbPrinter";private final Context mContext;private final UsbManager mUsbManager;private volatile List<UsbDevice> mUsbPrinterList = null;private static String ACTION_USB_PERMISSION = "com.posin.usbdevice.USB_PERMISSION";private com.posin.usbprinter.UsbPrinterUtil.OnUsbPermissionCallback onPermissionCallback = null;public static final byte[] PUSH_CASH = {0x1b, 0x70, 0x00, 0x1e, (byte) 0xff, 0x00};public UsbDeviceConnection mConnection;private UsbEndpoint mEndpointIntr;final BroadcastReceiver mReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {Log.d("UsbPrinter", intent.getAction());if (MyUsbPrinterUtil.ACTION_USB_PERMISSION.equals(intent.getAction())) {UsbDevice device = (UsbDevice) intent.getParcelableExtra("device");if (intent.getBooleanExtra("permission", false)) {if (MyUsbPrinterUtil.this.onPermissionCallback != null) {MyUsbPrinterUtil.this.onPermissionCallback.onUsbPermissionEvent(device, true);}} else if (MyUsbPrinterUtil.this.onPermissionCallback != null) {MyUsbPrinterUtil.this.onPermissionCallback.onUsbPermissionEvent(device, false);}context.unregisterReceiver(this);}}};public MyUsbPrinterUtil(Context context) {this.mContext = context;this.mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);}/*** 获取所有的小票打印机设备*/public List<UsbDevice> getUsbPrinterList() {//        if (Build.MODEL.substring(0, 3).equalsIgnoreCase("TPS")) {if (this.mUsbPrinterList == null) {this.mUsbPrinterList = this.findAllUsbPrinter();}return this.mUsbPrinterList;
//        } else {
//            Log.e("_ERROR", "ERROR--->Device is not support!  This Demo just developer for TPS device");
//            return null;
//        }}public boolean requestPermission(UsbDevice usbDevice, com.posin.usbprinter.UsbPrinterUtil.OnUsbPermissionCallback callback) {if (!this.mUsbManager.hasPermission(usbDevice)) {IntentFilter ifilter = new IntentFilter(ACTION_USB_PERMISSION);this.mContext.registerReceiver(this.mReceiver, ifilter);PendingIntent pi = PendingIntent.getBroadcast(this.mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);this.onPermissionCallback = callback;this.mUsbManager.requestPermission(usbDevice, pi);return false;} else {return true;}}/*** 获取所有的小票打印机*/private List<UsbDevice> findAllUsbPrinter() {List<UsbDevice> result = new ArrayList();Log.d("UsbPrinter", "find usb printer...");Iterator var3 = this.mUsbManager.getDeviceList().values().iterator();while (var3.hasNext()) {UsbDevice usbDevice = (UsbDevice) var3.next();Log.d("UsbPrinter", String.format("usb %04X:%04X : device_id=%d, device_name=%s", new Object[]{Integer.valueOf(usbDevice.getVendorId()), Integer.valueOf(usbDevice.getProductId()), Integer.valueOf(usbDevice.getDeviceId()), usbDevice.getDeviceName()}));if (isUsbPrinterDevice(usbDevice)) {Log.d("UsbPrinter", String.format("usb printer %04X:%04X : device_id=%d, device_name=%s", new Object[]{Integer.valueOf(usbDevice.getVendorId()), Integer.valueOf(usbDevice.getProductId()), Integer.valueOf(usbDevice.getDeviceId()), usbDevice.getDeviceName()}));result.add(usbDevice);}}return result;}/*** 识别不同的小票打印机设备** @param usbDevice* @return*/public static boolean isUsbPrinterDevice(UsbDevice usbDevice) {/*** getVendorId()返回一个供应商id*getProductId()为设备返回一个产品ID* */int vid = usbDevice.getVendorId();int pid = usbDevice.getProductId();return vid == 5455 && pid == 5455 || vid == 26728 && pid == 1280 || vid == 26728 && pid == 1536 || vid == '衦' || vid == 1137 || vid == 1659 || vid == 1137 || vid == 1155 && pid == 1803 || vid == 17224 || vid == 7358 || vid == 6790 || vid == 1046 && pid == 20497 || vid == 10685 || vid == 4070 && pid == 33054;}/* 打开钱箱 */public boolean pushReceiptCash() {boolean canPush = false;if (this.sendUsbCommand(PUSH_CASH)) {canPush = true;} else {canPush = false;}return canPush;}//发送信息 一是打印消息,切纸,打开钱箱等@SuppressLint("NewApi")public boolean sendUsbCommand(byte[] Content) {boolean Result;synchronized (this) {int len = -1;if (mConnection != null) {len = mConnection.bulkTransfer(mEndpointIntr, Content, Content.length, 10000);}if (len < 0) {Result = false;
//                Log.i(TAG, "发送失败! " + len);} else {Result = true;
//                Log.i(TAG, "发送" + len + "字节数据");}}return Result;}@SuppressLint("NewApi")public void setUsbDevice(UsbDevice device) {if (device != null) {UsbInterface intf = null;UsbEndpoint ep = null;int InterfaceCount = device.getInterfaceCount();Log.i(TAG, "InterfaceCount:" + InterfaceCount);int j;//            mDevice = device;for (j = 0; j < InterfaceCount; j++) {int i;intf = device.getInterface(j);Log.i(TAG, "接口是:" + j + "类是:" + intf.getInterfaceClass());if (intf.getInterfaceClass() == 7) {int UsbEndpointCount = intf.getEndpointCount();for (i = 0; i < UsbEndpointCount; i++) {ep = intf.getEndpoint(i);Log.i(TAG, "端点是:" + i + "方向是:" + ep.getDirection() + "类型是:" + ep.getType());if (ep.getDirection() == 0 && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {Log.i(TAG, "接口是:" + j + "端点是:" + i);break;}}if (i != UsbEndpointCount) {break;}}}if (j == InterfaceCount) {Log.i(TAG, "没有打印机接口");return;}mEndpointIntr = ep;UsbDeviceConnection connection = mUsbManager.openDevice(device);if (connection != null && connection.claimInterface(intf, true)) {Log.i(TAG, "打开成功! ");Log.i(TAG, "connection " + connection);mConnection = connection;} else {Log.i(TAG, "打开失败! ");mConnection = null;}}}@SuppressLint("NewApi")public void CloseReceiptUsb() {if (mConnection != null) {mConnection.close();mConnection = null;}}public interface OnUsbPermissionCallback {void onUsbPermissionEvent(UsbDevice var1, boolean var2);}
}
 

二、新建二维码打印方法类PrintCategory,代码如下:

import android.graphics.Bitmap;import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;import java.util.Hashtable;/*** Created by Administrator on 2018/1/6.* 这是小票打印类别类*/public class PrintCategory {/*** 生成条码、二维码** @param str       条码内容* @param type      条码类型: AZTEC, CODABAR, CODE_39, CODE_93, CODE_128, DATA_MATRIX,*                  EAN_8, EAN_13, ITF, MAXICODE, PDF_417, QR_CODE, RSS_14,*                  RSS_EXPANDED, UPC_A, UPC_E, UPC_EAN_EXTENSION;* @param bmpWidth  生成位图宽,宽不能大于384,不然大于打印纸宽度* @param bmpHeight 生成位图高,8的倍数*/public Bitmap CreateCode(String str, com.google.zxing.BarcodeFormat type, int bmpWidth, int bmpHeight)throws WriterException {Hashtable<EncodeHintType, String> mHashtable = new Hashtable<EncodeHintType, String>();mHashtable.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 生成二维矩阵,编码时要指定大小,不要生成了图片以后再进行缩放,以防模糊导致识别失败BitMatrix matrix = new MultiFormatWriter().encode(str, type, bmpWidth, bmpHeight, mHashtable);int width = matrix.getWidth();int height = matrix.getHeight();// 二维矩阵转为一维像素数组(一直横着排)int[] pixels = new int[width * height];for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {if (matrix.get(x, y)) {pixels[y * width + x] = 0xff000000;} else {pixels[y * width + x] = 0xffffffff;}}}Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 通过像素数组生成bitmap,具体参考apibitmap.setPixels(pixels, 0, width, 0, 0, width, height);return bitmap;}
}
 

三、新建打印方法类PrintReceived,调用此方法类直接打印,代码如下:

import android.graphics.Bitmap;import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.posin.usbprinter.UsbPrinter;import java.io.IOException;
import java.io.UnsupportedEncodingException;/*** Created by hboxs028 on 2018/1/30.* 这是小票打印类*/public class PrintReceipt {//打印的数据private static String cmd = "";public static boolean receiptPrint(final PrintfBean printfBean, int type) {Boolean print = (Boolean) ACache.get(App.getInstance().getApplicationContext()).getAsObject(Constants.WHETHER_PRINT);final UsbPrinter usbPrinter = App.getInstance().getUsbPrinter();final PrintCategory mPrintCategory = App.getInstance().getMpPrintCategory();if (usbPrinter == null) {ToastUtil.shortShow("小票打印机未连接");return false;} else {try {if ((print == null || !print)) {return false;}switch (type) {case TYPE_COLLECTION:cmd = productCollectFormat((CollectionPrintBean) printfBean);//收银订单/销售订单break;case TYPE_WEB_ORDER:cmd = webOrderFormat((WebOrderPrintBean) printfBean);//网络订单break;case TYPE_VIP_CARD:cmd = buyVipCardFormat((CollectionPrintBean) printfBean);break;case TYPE_TRANSFER:cmd = transferFormat((TransferPrintBean) printfBean);//交接班break;case TYPE_STOCK:cmd = strokFlowFormat((StockFlowPrintBean) printfBean);//货流通知break;case MEMBER_RECHARGE:cmd = memberRechargeFormat((MemberRechargePrintBean) printfBean);break;default:break;}new Thread() {@Overridepublic void run() {super.run();try {usbPrinter.resetInit();usbPrinter.selectAlignment(UsbPrinter.ALIGNMENT.LEFT);//设置对齐方式Bitmap qrBitMap = null;qrBitMap = mPrintCategory.CreateCode("http://www.hao123.com", BarcodeFormat.QR_CODE, 256, 256);//设置打印二维码的数据和宽高Bitmap barBitMap = mPrintCategory.CreateCode("201801050943308072", BarcodeFormat.CODE_128, 350, 40);//设置条形码的数据和宽高usbPrinter.selectFONT(UsbPrinter.FONT.FONT_A);//设置字体usbPrinter.selectBold(false);//设置是否加粗usbPrinter.selectUnderlined(false);//设置是否有下划线usbPrinter.doubleFontSize(false, false);//设置是否放大usbPrinter.setLineSpace(0);//设置间距usbPrinter.printString(cmd);//打印正文
//                            usbPrinter.selectAlignment(UsbPrinter.ALIGNMENT.RIGHT);//设置对齐方式
//                            usbPrinter.printBitmapByLine(barBitMap);//打印条形码
//                            usbPrinter.printBitmapByLine(qrBitMap);//打印二维码usbPrinter.walkPaper(3);//走纸usbPrinter.cutPaper();//切纸} catch (IOException e) {e.printStackTrace();} catch (WriterException e) {e.printStackTrace();} finally {try {sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return true;}}//打印测试public boolean printReceiptTest() {final UsbPrinter usbPrinter = App.getInstance().getUsbPrinter();final PrintCategory mPrintCategory = App.getInstance().getMpPrintCategory();if (usbPrinter == null) {ToastUtil.shortShow("小票打印机未连接");return false;} else {new Thread() {@Overridepublic void run() {super.run();try {usbPrinter.resetInit();usbPrinter.selectAlignment(UsbPrinter.ALIGNMENT.LEFT);//设置对齐方式Bitmap qrBitMap = null;qrBitMap = mPrintCategory.CreateCode("http://www.hao123.com", BarcodeFormat.QR_CODE, 256, 256);Bitmap barBitMap = mPrintCategory.CreateCode("201801050943308072", BarcodeFormat.CODE_128, 350, 40);usbPrinter.selectFONT(UsbPrinter.FONT.FONT_A);usbPrinter.selectBold(false);usbPrinter.selectUnderlined(false);usbPrinter.doubleFontSize(false, false);usbPrinter.setLineSpace(0);usbPrinter.printString("小票打印机打印测试\n");
//                        usbPrinter.printBitmapByLine(barBitMap);
//                        usbPrinter.selectAlignment(UsbPrinter.ALIGNMENT.RIGHT);
//                        usbPrinter.printBitmapByLine(qrBitMap);usbPrinter.walkPaper(3);usbPrinter.cutPaper();} catch (IOException e) {e.printStackTrace();} catch (WriterException e) {e.printStackTrace();} finally {try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();return true;}}}
 

注:如需要,可直接使用打印测试里面的代码,第一个方法是自己需要实现的方式,可根据打印测试里面的代码去实现自己想要的方式

四、连接方式

/*** 连接打印机*/
 
public static MyUsbPrinterUtil myUsbPrinterUtil = null;
private static List<UsbDevice> devices;
public static UsbPrinter usbPrinter = null;
public static PrintCategory mpPrintCategory = null;
 
private static ArrayList<UsbDevice> receiptDeviceList;
public static UsbDevice receiptUSBDevice;
/*** 连接打印机*/
public static void getReceiptDevice() {if (usbPrinter == null) {myUsbPrinterUtil = new MyUsbPrinterUtil(mContext);mpPrintCategory = new PrintCategory();devices = myUsbPrinterUtil.getUsbPrinterList();//获取所有打印设备receiptDeviceList = new ArrayList<>();for (UsbDevice usbDevice : devices) {if (myUsbPrinterUtil.isUsbPrinterDevice(usbDevice)) {myUsbPrinterUtil.requestPermission(usbDevice, null);//请求权限/*** 优库打印机:pid=33054 vid=4070* 君时达打印机:pid=1803 vid=1155* 票据打印机:pid=20497 vid=1046* 佳博打印机:pid=1536 vid=26728*/if (usbDevice.getVendorId() == 26728 && usbDevice.getProductId() == 1536 || usbDevice.getVendorId() == 4070 && usbDevice.getProductId() == 33054 ||usbDevice.getVendorId() == 1155 && usbDevice.getProductId() == 1803 || usbDevice.getVendorId() == 1046 && usbDevice.getProductId() == 20497) {receiptDeviceList.add(usbDevice);}}}if (receiptDeviceList.isEmpty()) {ToastUtil.shortShow(mContext.getResources().getString(R.string.no_connected));return;}receiptUSBDevice = receiptDeviceList.get(0);if (receiptUSBDevice == null) {receiptHandler.sendEmptyMessage(4);return;}try {usbPrinter = new UsbPrinter(mContext, receiptUSBDevice);//打印对象/*** 设置全局变量*/App.getInstance().setUsbPrinter(usbPrinter);App.getInstance().setMyUsbPrinterUtil(myUsbPrinterUtil);App.getInstance().setReceiptUSBDevice(receiptUSBDevice);App.getInstance().setMpPrintCategory(mpPrintCategory);receiptHandler.sendEmptyMessage(1);} catch (IOException e) {e.printStackTrace();}}
}

五、handle

// 用于接受连接状态消息的 Handler
@SuppressLint("HandlerLeak")
public static Handler receiptHandler = new Handler() {@SuppressLint("ShowToast")@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:ToastUtil.shortShow("连接成功");isConnected = true;Constants.ISCONNECTED = isConnected;break;case 2:isConnected = false;ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_failed));break;case 3:isConnected = false;Constants.ISCONNECTED = isConnected;Log.i(TAG, "连接关闭!");break;case 4:isConnected = false;ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_no));break;case 0:ToastUtil.shortShow("打印通信正常");break;case -1:ToastUtil.shortShow("打印机通信异常,请检查蓝牙连接");vibrator();break;case -2:ToastUtil.shortShow("打印缺纸");vibrator();break;case -3:ToastUtil.shortShow("打印机开盖");vibrator();break;default:break;}updateButtonState(isConnected);//更新打印机状态}
};
 

六、断开打印机

/*** 断开打印机连接*/
public static void breakPrinter() {if (usbPrinter != null) {/*** 断开打印设备的连接*/usbPrinter.close();usbPrinter = null;myUsbPrinterUtil.CloseReceiptUsb();myUsbPrinterUtil = null;mpPrintCategory = null;receiptDeviceList = null;receiptUSBDevice = null;App.getInstance().setUsbPrinter(null);App.getInstance().setMyUsbPrinterUtil(null);App.getInstance().setReceiptUSBDevice(null);App.getInstance().setMpPrintCategory(null);receiptHandler.sendEmptyMessage(3);ToastUtil.shortShow("已断开连接");} else {ToastUtil.shortShow("打印机未连接");}if (isConnected) {receipt_device_name.setText("设备名称: " + "小票打印机");receipt_print_state.setText(mContext.getResources().getString(R.string.on_line));} else {receipt_device_name.setText("设备名称:未连接");receipt_print_state.setText(mContext.getResources().getString(R.string.off_line));}}
 

以上就是连接的主要方法了,还有一些功能就根据自己的需要去实现了,只需要连接方法就基本解决掉了小票打印机的连接了

下面直接贴全部代码:

代码是在一个fragment里面点击按钮去连接,如需要啊activity中去连接,可直接设置,直接看点击事件里面的步骤就可实现。

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;import com.posin.usbprinter.UsbPrinter;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** 这是设置的打印小票机的设置*/
public class SettingBillPrinterFragment extends Fragment implements OnClickListener {//usb授权设置public UsbAdmin mUsbAdmin = null;private App app;private static TextView receipt_device_name;private RelativeLayout receipt_print_connect;private static TextView receipt_print_state;private RelativeLayout receipt_off_print;private RelativeLayout receipt_examine_print_state;private RelativeLayout receipt_print_test;private static Context mContext;private static ArrayList<UsbDevice> receiptDeviceList;public static UsbDevice receiptUSBDevice;public static boolean isConnected = false;protected static final String TAG = "SettingActivity";/***佳博小票打印机**/public static MyUsbPrinterUtil myUsbPrinterUtil = null;private static List<UsbDevice> devices;public static UsbPrinter usbPrinter = null;public static PrintCategory mpPrintCategory = null;
//    private Subscription subscribe;@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_setting_printer, container, false);receipt_device_name = view.findViewById(R.id.receipt_device_name);receipt_print_connect = view.findViewById(R.id.receipt_print_connect);receipt_print_state = view.findViewById(R.id.receipt_print_state);receipt_off_print = view.findViewById(R.id.receipt_off_print);receipt_examine_print_state = view.findViewById(R.id.receipt_examine_print_state);receipt_print_test = view.findViewById(R.id.receipt_print_test);receipt_print_connect.setOnClickListener(this);//连接打印机receipt_off_print.setOnClickListener(this);//断开打印机receipt_examine_print_state.setOnClickListener(this);//开钱箱receipt_print_test.setOnClickListener(this);//打印测试mContext = getActivity();updateButtonState(isConnected);app = (App) getActivity().getApplication();
//        mUsbAdmin = app.getUsbAdmin();ACache.get(getActivity()).put(Constants.WHETHER_PRINT, true);
//        myUsbPrinterUtil = App.getInstance().getMyUsbPrinterUtil();
//        usbPrinter = App.getInstance().getUsbPrinter();
//        receiptUSBDevice = App.getInstance().getReceiptUSBDevice();//        subscribe = RxBus.getDefault().toObservable(StateEvent.class).subscribe(new Action1<StateEvent>() {
//            @Override
//            public void call(StateEvent printEvent) {
//                isConnected = printEvent.isConnected();
//                Log.e("freak", isConnected + "bbb");
//                Log.e("freak", printEvent.isConnected() + "aaa");
//                updateButtonState(isConnected);
//            }
//        });return view;}@Overridepublic void onStart() {super.onStart();updateButtonState(isConnected);}@Overridepublic void onResume() {super.onResume();}@Overridepublic void onClick(View v) {switch (v.getId()) {//连接打印机case R.id.receipt_print_connect:getReceiptDevice();break;//断开打印机case R.id.receipt_off_print:breakPrinter();break;//开钱箱case R.id.receipt_examine_print_state:
//                if (HardwareUtil.pushCash(mUsbAdmin)) {
//                    ToastUtil.shortShow("测试结果:钱箱打开成功...");
//                } else {
//                    ToastUtil.shortShow("测试结果:钱箱打开失败...");
//                }if (usbPrinter == null) {ToastUtil.shortShow("小票打印机未连接");} else {myUsbPrinterUtil.setUsbDevice(receiptUSBDevice);if (myUsbPrinterUtil.pushReceiptCash()) {ToastUtil.shortShow("测试结果:钱箱打开成功...");myUsbPrinterUtil.CloseReceiptUsb();} else {ToastUtil.shortShow("测试结果:钱箱打开失败...");}}break;//打印测试case R.id.receipt_print_test:if (usbPrinter != null) {//                        myUsbPrinterUtil.setUsbDevice(receiptUSBDevice);new PrintReceipt().printReceiptTest();//                    new PrintReceipt().printReceiptTest(usbPrinter,mpPrintCategory);} else {ToastUtil.shortShow("小票打印机未连接");}break;}}/*** 断开打印机连接*/public static void breakPrinter() {if (usbPrinter != null) {/*** 断开打印设备的连接*/usbPrinter.close();usbPrinter = null;myUsbPrinterUtil.CloseReceiptUsb();myUsbPrinterUtil = null;mpPrintCategory = null;receiptDeviceList = null;receiptUSBDevice = null;App.getInstance().setUsbPrinter(null);App.getInstance().setMyUsbPrinterUtil(null);App.getInstance().setReceiptUSBDevice(null);App.getInstance().setMpPrintCategory(null);receiptHandler.sendEmptyMessage(3);ToastUtil.shortShow("已断开连接");} else {ToastUtil.shortShow("打印机未连接");}if (isConnected) {receipt_device_name.setText("设备名称: " + "小票打印机");receipt_print_state.setText(mContext.getResources().getString(R.string.on_line));} else {receipt_device_name.setText("设备名称:未连接");receipt_print_state.setText(mContext.getResources().getString(R.string.off_line));}}/*** 连接打印机*/public static void getReceiptDevice() {if (usbPrinter == null) {myUsbPrinterUtil = new MyUsbPrinterUtil(mContext);mpPrintCategory = new PrintCategory();devices = myUsbPrinterUtil.getUsbPrinterList();//获取所有打印设备receiptDeviceList = new ArrayList<>();for (UsbDevice usbDevice : devices) {if (myUsbPrinterUtil.isUsbPrinterDevice(usbDevice)) {myUsbPrinterUtil.requestPermission(usbDevice, null);//请求权限/*** 优库打印机:pid=33054 vid=4070* 君时达打印机:pid=1803 vid=1155* 票据打印机:pid=20497 vid=1046* 佳博打印机:pid=1536 vid=26728*/if (usbDevice.getVendorId() == 26728 && usbDevice.getProductId() == 1536 || usbDevice.getVendorId() == 4070 && usbDevice.getProductId() == 33054 ||usbDevice.getVendorId() == 1155 && usbDevice.getProductId() == 1803 || usbDevice.getVendorId() == 1046 && usbDevice.getProductId() == 20497) {receiptDeviceList.add(usbDevice);}}}if (receiptDeviceList.isEmpty()) {ToastUtil.shortShow(mContext.getResources().getString(R.string.no_connected));return;}receiptUSBDevice = receiptDeviceList.get(0);if (receiptUSBDevice == null) {receiptHandler.sendEmptyMessage(4);return;}try {usbPrinter = new UsbPrinter(mContext, receiptUSBDevice);//打印对象/*** 设置全局变量*/App.getInstance().setUsbPrinter(usbPrinter);App.getInstance().setMyUsbPrinterUtil(myUsbPrinterUtil);App.getInstance().setReceiptUSBDevice(receiptUSBDevice);App.getInstance().setMpPrintCategory(mpPrintCategory);receiptHandler.sendEmptyMessage(1);} catch (IOException e) {e.printStackTrace();}}}// 用于接受连接状态消息的 Handler@SuppressLint("HandlerLeak")public static Handler receiptHandler = new Handler() {@SuppressLint("ShowToast")@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:ToastUtil.shortShow("连接成功");isConnected = true;Constants.ISCONNECTED = isConnected;break;case 2:isConnected = false;ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_failed));break;case 3:isConnected = false;Constants.ISCONNECTED = isConnected;Log.i(TAG, "连接关闭!");break;case 4:isConnected = false;ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_no));break;case 0:ToastUtil.shortShow("打印通信正常");break;case -1:ToastUtil.shortShow("打印机通信异常,请检查蓝牙连接");vibrator();break;case -2:ToastUtil.shortShow("打印缺纸");vibrator();break;case -3:ToastUtil.shortShow("打印机开盖");vibrator();break;default:break;}updateButtonState(isConnected);//更新打印机状态}};static int count = 0;public static void vibrator() {count++;PrefUtils.setInt(mContext, "count3", count);Log.e(TAG, "" + count);}/*** 更新状态** @param isConnected*/public static void updateButtonState(boolean isConnected) {if (isConnected) {receipt_device_name.setText("设备名称: " + "小票打印机");receipt_print_state.setText(mContext.getResources().getString(R.string.on_line));} else {receipt_print_state.setText(mContext.getResources().getString(R.string.off_line));receipt_device_name.setText("设备名称:未连接");}PrefUtils.setBoolean(mContext, Constants.CONNECTSTATE, isConnected);}public void onDestroy() {super.onDestroy();
//        subscribe.unsubscribe();}}
 

最后,这个方法是需要使用打印sdk去实现的,如果真实需要实现打印sdk的朋友,可以留言给我,我给你们下载地址,毕竟自己在小票打印连接的坑了蹲了很久,给一些同样掉进这个坑里面的开发朋友一些帮助!

小票打印机sdk下载地址:https://download.csdn.net/download/freak_csh/10836232

demo:硬件系列导航与所有硬件博文的demo

硬件系列(五)-------------Android小票打印机连接 (已封装好,可直接使用)相关推荐

  1. Xamarin Getting Started翻译系列五--Android资源

    Android资源 本文介绍XamarinAndroid中的Android资源概念,以及如何使用资源.讨论如何使用资源实现应用程序本地化,多种设备支持如各种屏幕大小和密度. This article ...

  2. 京瓷1110打印自检页_如何修改小票打印机、厨房打印机IP地址

    如何修改小票打印机.厨房打印机IP地址 在商业收银活动中,小票打印机是必不可少的设备,不管超市收银系统还是餐饮收银系统,都是常用设备.易坏设备,刚开业时购买的成套的收银设备,商家一般都给设置好小票机, ...

  3. 社会化登录分享-Android SDK的二次封装和使用

    本系列文章将第三方的登录分享功能进行二次封装,统一接口调用,简化了接不同平台登录分享的步骤. 0 系列文章 系列一 Android SDK的二次封装和使用 系列二 源码解析 系列三 微信SDK接入 系 ...

  4. 硬件系列(四)-------------Android标签打印机连接与打印位置调动方法总结

    一.获取连接的标签打印设备 private static List<UsbDevice> deviceList; private static String deviceArrayLisr ...

  5. android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打印功能进行了封装,让你超快实现蓝牙打印功能

    BluetoothPrint 项目地址:liuGuiRong18/BluetoothPrint  简介:android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打 ...

  6. Android 平板通过USB口连接小票打印机

    1.首先注册一个广播:用户三种操作会导致系统发广播,插或者拔USB设备,还有就是在USB授权框点击是或者否 private void initReceiver() {//授权对话框点击操作之后会发出系 ...

  7. 硬件系列(二)-------------wifi打印机之佳博wifi打印机踩坑之路

    一.前言 之前做过USB打印机,但是现在需求变了,不是使用收银台进行打印机的连接了,而是使用手机与打印机进行打印.手机又无法像收银机一样直接使用USB直接与打印机直接连接进行打印.所以只能使用蓝牙打印 ...

  8. Uniapp Android 佳博 小票打印机 插件

    Uniapp Android 佳博 小票打印机 插件 Uniapp Android 佳博小票打印机插件:  支持图片.条型码.二维码 打印. 1. 实例化插件 const gp= uni.requir ...

  9. 硬件系列(三)--------wifi打印机之使用socket打印(无sdk)

    一.前言 在上一篇博文 硬件系列(二)-------------wifi打印机之佳博wifi打印机踩坑之路中介绍了佳博wifi打印机的打印,但是这个是要的是sdk进行打印的,如果没有sdk呢?所以,这 ...

最新文章

  1. 量子通信是不是伪科学?潘建伟这样回应
  2. vue.use无非就是为Vue对象注入新的方法和属性
  3. 大数据征信应用与启示 ——以美国互联网金融公司 ZestFinance为例
  4. 互联网金融售前心得数据脱敏分析 | PMCAFF微分享
  5. 北斗导航 | 北斗RDSS短报文通信及定位原理(RD双星定位、通信与授时、附代码)
  6. 计算机信息安全专业留学,2021美国信息安全专业排名Top50大学!
  7. C++ vector容器类型 (摘自漫步云端的博客)
  8. c语言多个子函数声明,C函数在多个源文件中的声明和定义
  9. 【java】java 新一代垃圾回收器ZGC的探索与实践
  10. 基于CentOS7.3构建企业级Vsftpd文件服务器
  11. Spark技术内幕:Master基于ZooKeeper的High Availability(HA)源代码实现
  12. ftp等远程登录工具的星号密码查看方法
  13. 3次根号计算机在线应用,根号计算器,三次根号计算器
  14. 《中国品牌故事》讲述中节能品牌故事:皓日初升
  15. python实现舒尔特方格
  16. 好不容易说明白AQS,面试官却还要我说应用场景,我只好又讲了CountDownLatch ~~~
  17. 【转帖】赤壁之战,曹操大败只因缺了Service Mesh
  18. c语言直线插补原理程序,直线插补算法
  19. 白光迈克尔逊干涉仪的仿真
  20. Factoryio的应用

热门文章

  1. 山东省高中学业水平考试计算机考试教材,2017年山东高中学业水平考试科目
  2. transformer 模型的decoder部分 带gif动图
  3. 开源项目之Android 向下刷新列表
  4. java word转html乱码怎么办,poi导出word 乱码 poi word转html 乱码
  5. 三个显示图像的matlab函数图像,如何在matlab中将三个隐函数图像画在同一个图上...
  6. remove debug symbols to a seperate file
  7. java培训班值得去吗?
  8. [每天一个知识点]12-Maven怎么读
  9. 记一次jstack线程诊断
  10. 偷偷告诉你中国小姐姐的真实Size!!