Android小票打印机连接 (已封装好,可直接使用)

一、新建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,具体参考api
        bitmap.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() {
                    @Override
                    public 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() {
                @Override
                public 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 block
                            e.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")
    @Override
    public 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);//更新打印机状态
    }
};

六、断开打印机

扫描二维码关注公众号,回复: 1830122 查看本文章

/**
 * 断开打印机连接
 */
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;


    @Override
    public 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;
    }

    @Override
    public void onStart() {
        super.onStart();

        updateButtonState(isConnected);
    }

    @Override
    public void onResume() {
        super.onResume();
    }



    @Override
    public 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")
        @Override
        public 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的朋友,可以留言给我,我给你们下载地址,毕竟自己在小票打印连接的坑了蹲了很久,给一些同样掉进这个坑里面的开发朋友一些帮助!




猜你喜欢

转载自blog.csdn.net/freak_csh/article/details/79626139
今日推荐