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

一、获取连接的标签打印设备

 

private static List<UsbDevice> deviceList;
private static String deviceArrayLisr;
private static UsbDevice mUSBDevice;
public static PrinterInstance myPrinter;
public static String devicesName = "未知设备";
private static String devicesAddress;
private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
 
public static boolean isConnected = false;
public static void getDevice() {
    if (myPrinter == null) {
        /**
         * 检测所有的打印设备
         */
        UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);//获取usb权限
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        deviceList = new ArrayList<>();
        for (UsbDevice device : devices.values()) {
            /**
             * 判断是都是打印设备。目前支持 (1155 != vendorId || 22304 != productId) && (1659 != vendorId || 8965 != productId) 两种
             */
            if (USBPort.isUsbPrinter(device)) {
                if (device.getVendorId() == 1155 && device.getProductId() == 22304) {
                    deviceArrayLisr = device.getDeviceName() + "\nvid: "
                            + device.getVendorId() + " pid: "
                            + device.getProductId();
                    deviceList.add(device);
                }

            }
        }


        if (deviceList.isEmpty()) {
            ToastUtil.shortShow(mContext.getResources().getString(R.string.no_connected));
            return;
        }
        mUSBDevice = deviceList.get(0);
        if (mUSBDevice == null) {
            mHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
            return;
        }
        myPrinter = PrinterInstance.getPrinterInstance(mContext, mUSBDevice, mHandler);
        devicesName = mUSBDevice.getDeviceName();
        devicesAddress = "vid: " + mUSBDevice.getVendorId() + "  pid: " + mUSBDevice.getProductId();
        UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        if (mUsbManager.hasPermission(mUSBDevice)) {
            myPrinter.openConnection();
        } else {
            // 没有权限询问用户是否授予权限
            PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            mContext.registerReceiver(mUsbReceiver, filter);
            mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后,系统弹出一个对话框
        }

    }

}

二、handle

 

// 用于接受连接状态消息的 Handler
@SuppressLint("HandlerLeak")
public static Handler mHandler = new Handler() {
    @SuppressLint("ShowToast")
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {

            case PrinterConstants.Connect.SUCCESS:

                ToastUtil.shortShow("连接成功");

                isConnected = true;
                Constants.ISCONNECTED = isConnected;
                Constants.DEVICE_NAME = devicesName;
                break;

            case PrinterConstants.Connect.FAILED:
                isConnected = false;
                ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_failed));
                Log.i(TAG, "连接失败!");
                break;

            case PrinterConstants.Connect.CLOSED:
                isConnected = false;
                Constants.ISCONNECTED = isConnected;
                Constants.DEVICE_NAME = devicesName;
                Log.i(TAG, "连接关闭!");
                break;
            case PrinterConstants.Connect.NODEVICE:
                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);//此方法用于更新ui,更新打印机的连接状态
    }
};

三、receiver

 

private static final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    @Override
    @SuppressLint("NewApi")
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.w(TAG, "receiver action: " + action);

        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                mContext.unregisterReceiver(mUsbReceiver);
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                        && mUSBDevice.equals(device)) {
                    myPrinter.openConnection();
                } else {
                    mHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
                    Log.e(TAG, "permission denied for device " + device);
                }
            }
        }
    }
};

四、使用了广播要在onDestroy方法中关闭

 

public void onDestroy() {
    XLog.e(TAG, "yxz at SettingActivity.java onDestroy()   progressdialog");
    super.onDestroy();
    if (hasRegDisconnectReceiver) {
        mContext.unregisterReceiver(mUsbReceiver);
        hasRegDisconnectReceiver = false;
        // Log.i(TAG, "关闭了广播!");
    }
}

五、断开连接

 

    /**
     * 断开连接
     */
    public static void breakPrinter() {
        if (myPrinter != null) {
            /**
             * 断开打印设备的连接
             */
            myPrinter.closeConnection();
            myPrinter = null;//清空打印对象
            XLog.i(TAG, "yxz at SettingActivity.java  onClick()  mPrinter:" + myPrinter);
        }
        if (isConnected) {
            tv_device_name.setText("设备名称: " + "思普瑞特价签机");
            label_print_state.setText(mContext.getResources().getString(R.string.on_line));
        } else {
            tv_device_name.setText("设备名称:未连接");
            label_print_state.setText(mContext.getResources().getString(R.string.off_line));
        }
//    label_print_state.setText(mContext.getResources().getString(R.string.off_line));
        ToastUtil.shortShow("已断开连接");
    }

六、打印方法

 

import android.content.Context;


import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterConstants.PAlign;
import com.printer.sdk.PrinterConstants.PBarcodeType;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.exception.ParameterErrorException;
import com.printer.sdk.exception.PrinterPortNullException;
import com.printer.sdk.exception.WriteException;

import org.apache.http.util.TextUtils;

import java.util.List;


public class PrintLabelGaomi {

    //多个打印
    public void doPrintTSPL(final PrinterInstance iPrinter, final Context mContext, final List<ProductLabelBean> productLabelBeanList) {
        final boolean printer_direction = (boolean) ACache.get(mContext.getApplicationContext()).getAsObject(Constants.PRINT_DIRECTION);
        android.util.Log.d("cai", "是否打印" + printer_direction);

        new Thread() {
            @Override
            public void run() {

                for (ProductLabelBean p : productLabelBeanList) {

                    int left = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "leftmargin", 0);
                    int top = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "topmargin", 0);
                    int numbers = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "printnumbers", 1);
                    int isBeep = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "isBeep", 0);

                    try {
                        // 设置标签纸大小 型号SIZE_58mm 尺寸56 * 8:45 * 8
                        //45
                        iPrinter.pageSetupTSPL(PrinterConstants.SIZE_80mm, 80 * 8, 50 * 8);

                        // 清除缓存区内容
                        iPrinter.printText("CLS\r\n");

                        // 设置标签的参考坐标原点
                        if (left == 0 || top == 0) {
                            // 不做设置,默认
                        } else {
                            iPrinter.sendStrToPrinterTSPL("REFERENCE " + left * 8 + "," + top * 8 + "\r\n");
                        }

                        /**
                         * x 是代表横的位置 ;y是行数,从0开始
                         * 前4 表明开始的位置 xy,开始和结束的位置
                         * 56 表明放置的位置
                         * 7 表明是简体中文
                         * 89 表明是xy的倍数:表明字体的大小
                         * 10 表明是是否旋转
                         * 11 表明是需要打印的字体
                         * */
                        /**
                         * 初始版
                         */

                        if (printer_direction) {

                            /**
                             * 以下为最终版
                             * 旋转180度
                             */
                            //名称
                            if (TextUtils.isEmpty(p.getName())){
                                iPrinter.drawTextTSPL(50 * 8, 40 * 8 + 10, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(50 * 8, 40 * 8 + 10, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getName());
                            }
                            // 横线上方区域右侧的文字
                        
                            if (TextUtils.isEmpty(p.getPrice())){
                                iPrinter.drawTextTSPL(33 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(33 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, p.getPrice());
                            }
                            // 横线上方区域右侧的文字 ,空格间隔
                            //
//                        iPrinter.drawTextTSPL(25 * 8, 11 * 8, 40 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCashAndEPrice());
                            //会员价 TODO 已取消
//                            iPrinter.drawTextTSPL(33 * 8, 14 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCash());
                            //   最大数据个数限制为5位  例如:99.99
                            if (TextUtils.isEmpty(p.getEprice())){
                                iPrinter.drawTextTSPL(17 * 8, 14 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(17 * 8, 14 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getEprice());
                            }
                            //计量单位
                            if (TextUtils.isEmpty(p.getUnit())){
                                iPrinter.drawTextTSPL(60 * 8, 20 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(60 * 8, 20 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getUnit());
                            }
                            // 二维码下方的一维条码 13位
                            // 14,15,16,17,18 no 12
                            //sn
                            if (TextUtils.isEmpty(p.getSn())){
                                iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSn());
                            }
                            //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                            iPrinter.drawBarCodeTSPL(75 * 8, 10 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
                            iPrinter.drawBarCodeTSPL(75*8, 10 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, PrinterConstants.PRotate.Rotate_180, 1, 1, p.getSn());

                            //以下三条数据是不打印的,只是打印空格
                            //规格
                            if (TextUtils.isEmpty(p.getSpecification())){
                                iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSpecification());
                            }
                            // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
                           
                            if (TextUtils.isEmpty(p.getProducer())){
                                iPrinter.drawTextTSPL(65 * 8, 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(65 * 8, 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getProducer());
                            }
                         
                            if (TextUtils.isEmpty(p.getRank())){
                                iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                            }else {
                                iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getRank());
                            }
                           
                            if (TextUtils.isEmpty(p.getSupervisor())){
                                iPrinter.drawTextTSPL(14 * 8, 5 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");

                            }else {
                                iPrinter.drawTextTSPL(14 * 8, 5 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSupervisor());
                            }

                        } else {
                          
                            if (TextUtils.isEmpty(p.getName())){
                                iPrinter.drawTextTSPL(30 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, " ");
                            }else {
                                iPrinter.drawTextTSPL(30 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getName());
                            }
                            // 横线上方区域右侧的文字
                            
                            if (TextUtils.isEmpty(p.getPrice())){
                                iPrinter.drawTextTSPL(48 * 8, 23 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, " ");
                            }else {
                                iPrinter.drawTextTSPL(48 * 8, 23 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, p.getPrice());
                            }
                            // 横线上方区域右侧的文字 价格和E币,空格间隔
                          
//                        iPrinter.drawTextTSPL(49 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, null, p.getCashAndEPrice());
                           
//                            iPrinter.drawTextTSPL(47 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getCash());
                           
                            if (TextUtils.isEmpty(p.getEprice())){
                                iPrinter.drawTextTSPL(63 * 8, 38 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, " ");

                            }else {
                                iPrinter.drawTextTSPL(63 * 8, 38 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getEprice());

                            }

                        
                            if (TextUtils.isEmpty(p.getUnit())){
                                iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, " ");
                            }else {
                                iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getUnit());
                            }
                            // 二维码下方的一维条码 13位
                            // 14,15,16,17,18 no 12
                          
                            if (TextUtils.isEmpty(p.getSn())){
                                iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, " ");
                            }else {
                                iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSn());
                            }

                            //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
                            iPrinter.drawBarCodeTSPL(40, 40 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());

                          
                            if (TextUtils.isEmpty(p.getSupervisor())){
                                iPrinter.drawTextTSPL(65 * 8, 47 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, " ");
                            }else {
                                iPrinter.drawTextTSPL(65 * 8, 47 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSupervisor());
                            }

                        }
//                   
//                        iPrinter.drawTextTSPL(14 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getName());
//
//                        // 横线上方区域右侧的文字
//                       
//                        iPrinter.drawTextTSPL(48 * 8, 23 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, p.getPrice());
//
//                        // 横线上方区域右侧的文字 价格和E币,空格间隔
//                       
//                        iPrinter.drawTextTSPL(49 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, null, p.getCashAndEPrice());
//
//                    
//                        iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getUnit());
//
//                        // 二维码下方的一维条码 13位
//                        // 14,15,16,17,18 no 12
//                      
//                        iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSn());
//
//                        //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                        iPrinter.drawBarCodeTSPL(40, 40 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());


//                        /**
//                         * 以下为最终版
//                         */
//                      
//                        iPrinter.drawTextTSPL(50 * 8, 40 * 8+10, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getName());
//
//                        // 横线上方区域右侧的文字
//                 
//                        iPrinter.drawTextTSPL(33 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, p.getPrice());
//
//                        // 横线上方区域右侧的文字 价格和E币,空格间隔
//                      
                        iPrinter.drawTextTSPL(25 * 8, 11 * 8, 40 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCashAndEPrice());
//                       
//                        iPrinter.drawTextTSPL(33 * 8, 14 * 8+2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCash());
//                        //   最大数据个数限制为5位  例如:99.99
//                        iPrinter.drawTextTSPL(17 * 8, 14 * 8+2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getEprice());
//
//                       
//                        iPrinter.drawTextTSPL(60 * 8, 20 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getUnit());
//
//                        // 二维码下方的一维条码 13位
//                        // 14,15,16,17,18 no 12
//                        
//                        iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSn());
//
//                        //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                        iPrinter.drawBarCodeTSPL(75*8, 10 * 8+4  , PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
//                        //以下三条数据是不打印的,只是打印空格
//                       
//                        iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
//                        // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
//                       
//                        iPrinter.drawTextTSPL(65 * 8 , 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180," ");
//
//                     
//                        iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");


                        // 判断是否响应蜂鸣器
                        if (isBeep == 1) {
                            // 打印前响
                            iPrinter.beepTSPL(1, 1000);
                            Thread.sleep(3000);
                            // 打印
                            iPrinter.printTSPL(numbers, 1);
                        } else if (isBeep == 2) {
                            // 打印
                            iPrinter.printTSPL(numbers, 1);
                            // 打印后响
                            iPrinter.beepTSPL(1, 1000);
                        } else {
                            // 打印
                            iPrinter.printTSPL(numbers, 1);
                        }

                    } catch (WriteException e) {
                        e.printStackTrace();
                    } catch (PrinterPortNullException e) {
                        e.printStackTrace();
                    } catch (ParameterErrorException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        }.start();
    }


//    //多个打印
//    public void doPrintTSPL(final PrinterInstance iPrinter, final Context mContext, final List<ProductLabelBean> productLabelBeanList) {
//        new Thread() {
//            @Override
//            public void run() {
//
//                for (ProductLabelBean p : productLabelBeanList) {
//
//                    int left = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "leftmargin", 0);
//                    int top = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "topmargin", 0);
//                    int numbers = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "printnumbers", 1);
//                    int isBeep = com.android.hboxs.gaomicashier.common.hardware.label.PrefUtils.getInt(mContext, "isBeep", 0);
//
//                    try {
//                        // 设置标签纸大小 型号SIZE_58mm 尺寸56 * 8:45 * 8
//                        //45
//                        iPrinter.pageSetupTSPL(PrinterConstants.SIZE_80mm, 80 * 8, 50 * 8);
//
//                        // 清除缓存区内容
//                        iPrinter.printText("CLS\r\n");
//
//                        // 设置标签的参考坐标原点
//                        if (left == 0 || top == 0) {
//                            // 不做设置,默认
//                        } else {
//                            iPrinter.sendStrToPrinterTSPL("REFERENCE " + left * 8 + "," + top * 8 + "\r\n");
//                        }
//
//                        /**
//                         * x 是代表横的位置 ;y是行数,从0开始
//                         * 前4 表明开始的位置 xy,开始和结束的位置
//                         * 56 表明放置的位置
//                         * 7 表明是简体中文
//                         * 89 表明是xy的倍数:表明字体的大小
//                         * 10 表明是是否旋转
//                         * 11 表明是需要打印的字体
//                         * */
//
//                    
//                        iPrinter.drawTextTSPL(14 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getName());
//
//                        // 横线上方区域右侧的文字
//                       
//                        iPrinter.drawTextTSPL(48 * 8, 23 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, p.getPrice());
//
//                        // 横线上方区域右侧的文字 价格和积分,空格间隔
//                       
//                        iPrinter.drawTextTSPL(49 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, null, p.getCashAndEPrice());
//
//                     
//                        iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getUnit());
//
//                        // 二维码下方的一维条码 13位
//                        // 14,15,16,17,18 no 12
//                       
//                        iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSn());
//
//                        //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                        iPrinter.drawBarCodeTSPL(40, 40 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
//
//                        // 判断是否响应蜂鸣器
//                        if (isBeep == 1) {
//                            // 打印前响
//                            iPrinter.beepTSPL(1, 1000);
//                            Thread.sleep(3000);
//                            // 打印
//                            iPrinter.printTSPL(numbers, 1);
//                        } else if (isBeep == 2) {
//                            // 打印
//                            iPrinter.printTSPL(numbers, 1);
//                            // 打印后响
//                            iPrinter.beepTSPL(1, 1000);
//                        } else {
//                            // 打印
//                            iPrinter.printTSPL(numbers, 1);
//                        }
//
//                    } catch (WriteException e) {
//                        e.printStackTrace();
//                    } catch (PrinterPortNullException e) {
//                        e.printStackTrace();
//                    } catch (ParameterErrorException e) {
//                        e.printStackTrace();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            }
//
//        }.start();
//    }

//    //打印测试
//    public void doPrintTSPL(final PrinterInstance iPrinter, final Context mContext, final ProductLabelBean p) {
//        new Thread() {
//            @Override
//            public void run() {
//
//                int left = PrefUtils.getInt(mContext, "leftmargin", 0);
//                int top = PrefUtils.getInt(mContext, "topmargin", 0);
//                int numbers = PrefUtils.getInt(mContext, "printnumbers", 1);
//                int isBeep = PrefUtils.getInt(mContext, "isBeep", 0);
//
//                try {
//                    // 设置标签纸大小 型号SIZE_58mm 尺寸56 * 8:45 * 8
//                    iPrinter.pageSetupTSPL(PrinterConstants.SIZE_80mm, 80 * 8, 50 * 8);
//
//                    // 清除缓存区内容
//                    iPrinter.printText("CLS\r\n");
//
//                    // 设置标签的参考坐标原点
//                    if (left == 0 || top == 0) {
//                        // 不做设置,默认
//                    } else {
//                        iPrinter.sendStrToPrinterTSPL("REFERENCE " + left * 8 + "," + top * 8 + "\r\n");
//                    }
//
//                    /**
//                     * x 是代表横的位置 ;y是行数,从0开始
//                     * 前4 表明开始的位置 xy,开始和结束的位置
//                     * 56 表明放置的位置
//                     * 7 表明是简体中文
//                     * 89 表明是xy的倍数:表明字体的大小
//                     * 10 表明是是否旋转
//                     * 11 表明是需要打印的字体
//                     * */
//
//                
//                    iPrinter.drawTextTSPL(14 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getName());
//
//                    // 横线上方区域
//                   
//                    iPrinter.drawTextTSPL(12 * 8, 19 * 8 + 4, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, "规格1");
//                    // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
//                  
//                    iPrinter.drawTextTSPL(11 * 8 + 4, 26 * 8, 25 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getProducer());
//
//                  
//                    iPrinter.drawTextTSPL(31 * 8, 26 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, "一级品");
//
//                    // 横线上方区域右侧的文字
//                    
//                    iPrinter.drawTextTSPL(48 * 8, 24 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, p.getPrice());
//
//                    // 横线上方区域右侧的文字 价格和积分,空格间隔
//                  
//                    iPrinter.drawTextTSPL(49 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, null, p.getCashAndEPrice());
//
//                 
//                    iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getUnit());
//
//                    // 二维码下方的一维条码 13位
//                  
//                    iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSn());
//
//                    //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                    iPrinter.drawBarCodeTSPL(40, 40 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
//
//                    // 判断是否响应蜂鸣器
//                    if (isBeep == 1) {
//                        // 打印前响
//                        iPrinter.beepTSPL(1, 1000);
//                        Thread.sleep(3000);
//                        // 打印
//                        iPrinter.printTSPL(numbers, 1);
//                    } else if (isBeep == 2) {
//                        // 打印
//                        iPrinter.printTSPL(numbers, 1);
//                        // 打印后响
//                        iPrinter.beepTSPL(1, 1000);
//                    } else {
//                        // 打印
//                        iPrinter.printTSPL(numbers, 1);
//                    }
//
//                } catch (WriteException e) {
//                    e.printStackTrace();
//                } catch (PrinterPortNullException e) {
//                    e.printStackTrace();
//                } catch (ParameterErrorException e) {
//                    e.printStackTrace();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//        }.start();
//    }


    //打印测试
    public void doPrintTSPL(final PrinterInstance iPrinter, final Context mContext, final ProductLabelBean p) {
        final boolean printer_direction = (boolean) ACache.get(mContext.getApplicationContext()).getAsObject(Constants.PRINT_DIRECTION);
        android.util.Log.d("cai", "是否打印" + printer_direction);
        new Thread() {
            @Override
            public void run() {

                int left = PrefUtils.getInt(mContext, "leftmargin", 0);
                int top = PrefUtils.getInt(mContext, "topmargin", 0);
                int numbers = PrefUtils.getInt(mContext, "printnumbers", 1);
                int isBeep = PrefUtils.getInt(mContext, "isBeep", 0);
                int printlevel=PrefUtils.getInt(mContext,"printlevel",7);

                try {
                    // 设置标签纸大小 型号SIZE_58mm 尺寸56 * 8:45 * 8
                    iPrinter.pageSetupTSPL(PrinterConstants.SIZE_80mm, 80 * 8, 50 * 8);

                    // 清除缓存区内容
                    iPrinter.printText("CLS\r\n");

                    // 设置标签的参考坐标原点
                    if (left == 0 || top == 0) {
                        // 不做设置,默认
                    } else {
                        iPrinter.sendStrToPrinterTSPL("REFERENCE " + left * 8 + "," + top * 8 + "\r\n");
                    }

                    /**
                     * x 是代表横的位置 ;y是行数,从0开始
                     * 前4 表明开始的位置 xy,开始和结束的位置
                     * 56 表明放置的位置
                     * 7 表明是简体中文
                     * 89 表明是xy的倍数:表明字体的大小
                     * 10 表明是是否旋转
                     * 11 表明是需要打印的字体
                     * */


//                   
//                    iPrinter.drawTextTSPL(50 * 8, 40 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getName());
//
//                    // 横线上方区域
//                  
//                    iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, "规格1");
//                    // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
//                   
//                    iPrinter.drawTextTSPL(65 * 8 , 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getProducer());
//
//                  
//                    iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, "一级品");
//
//                    // 横线上方区域右侧的文字
//               
//                    iPrinter.drawTextTSPL(30 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, p.getPrice());
//
//                    // 横线上方区域右侧的文字 价格和E币,空格间隔
//                   
//                    iPrinter.drawTextTSPL(25 * 8, 11 * 8, 40 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCashAndEPrice());
//
//                    
//                    iPrinter.drawTextTSPL(60 * 8, 16 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getUnit());
//
//                    // 二维码下方的一维条码 13位
//                  
//                    iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSn());
//
//                    //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                    iPrinter.drawBarCodeTSPL(75*8, 10 * 8 , PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());


                    /**
                     * 1、对应开始位置的x坐标
                     * 2、对应开始位置的y坐标
                     * 3、对应结束位置的x坐标
                     * 4、对应结束位置的y坐标
                     * 5、x坐标的对齐方式
                     * 6、y坐标的对齐方式
                     * 7、是否是简体中文
                     * 8、x字体大小
                     * 9、y字体大小
                     * 10、旋转方式
                     * 11、打印的数据
                     */
                    /***
                     * 第二版最、最终版
                     */
//                    // 最大数据个数限制为10位
//                    iPrinter.drawTextTSPL(50 * 8, 40 * 8+10, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getName());
//                    //  最大数据个数限制为10位  例如:3000000.01
//
//                    iPrinter.drawTextTSPL(33 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, p.getPrice());
//                    // 横线上方区域右侧的文字 价格和E币,空格间隔
//                    // 最大数据个数限制为8位  例如:200000.01
//
//                    iPrinter.drawTextTSPL(33 * 8, 14 * 8+2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCash());
//                    //   最大数据个数限制为5位  例如:99.99
//                    iPrinter.drawTextTSPL(17 * 8, 14 * 8+2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getEprice());
//
//                    // 字数最大限制为6位
//                    iPrinter.drawTextTSPL(60 * 8, 20 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, "包");
//
//                    // 二维码下方的一维条码 13位
//                    
//                    /***
//                     * 上面有
//                     */
//                    iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSn());
//                    /***
//                     * 上面有
//                     */
//                    //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
//                    iPrinter.drawBarCodeTSPL(75*8, 10 * 8+4 , PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
//                    // 横线上方区域
//                    //
//                    iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
//                    // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
//                    
//                    iPrinter.drawTextTSPL(65 * 8 , 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180," ");
//
//                  
//                    iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");

//                    // 横线上方区域右侧的文字

                    /**
                     * 测试一、二版结合选择
                     */

                    if (printer_direction) {

                        /**
                         * 以下为最终版
                         * 旋转版
                         */
                        //名称
                        iPrinter.drawTextTSPL(50 * 8, 40 * 8 + 10, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getName());

                        // 横线上方区域右侧的文字
                       
                        iPrinter.drawTextTSPL(33 * 8, 28 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, PrinterConstants.PRotate.Rotate_180, p.getPrice());

                        // 横线上方区域右侧的文字 价格和E币,空格间隔
                       
//                        iPrinter.drawTextTSPL(25 * 8, 11 * 8, 40 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCashAndEPrice());
                       
                        iPrinter.drawTextTSPL(33 * 8, 14 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getCash());
                        //  最大数据个数限制为5位  例如:99.99
                        iPrinter.drawTextTSPL(17 * 8, 14 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, PrinterConstants.PRotate.Rotate_180, p.getEprice());

                     
                        iPrinter.drawTextTSPL(60 * 8, 20 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getUnit());

                        // 二维码下方的一维条码 13位
                        // 14,15,16,17,18 no 12
                
                        iPrinter.drawTextTSPL(60 * 8, 14 * 8 + 2, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, p.getSn());

                        //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
                        iPrinter.drawBarCodeTSPL(75*8, 10 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, PrinterConstants.PRotate.Rotate_180, 1, 1, p.getSn());
                        //以下三条数据是不打印的,只是打印空格
                  
                        iPrinter.drawTextTSPL(60 * 8, 30 * 8 + 4, 70 * 8, 7 * 8, PAlign.CENTER, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                        // 横线上方区域左下方的文字 ((0,0)(40*8,7*8))
                 
                        iPrinter.drawTextTSPL(65 * 8, 25 * 8, 75 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");

                     
                        iPrinter.drawTextTSPL(48 * 8, 25 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, " ");
                       //TODO:2018-02-10 需要调试位置
                       
                        iPrinter.drawTextTSPL(14 * 8, 5 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, PrinterConstants.PRotate.Rotate_180, "物价员");
                    } else {
                        /**
                         * 不旋转版
                         */
                     
                        iPrinter.drawTextTSPL(17 * 8, 11 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getName());

                        // 横线上方区域右侧的文字
                   
                        iPrinter.drawTextTSPL(48 * 8, 23 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 2, 2, null, p.getPrice());

                        // 横线上方区域右侧的文字 ,空格间隔
                       
                        iPrinter.drawTextTSPL(47 * 8, 38 * 8, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getCash());
                   
                        iPrinter.drawTextTSPL(63 * 8, 38 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 2, null, p.getEprice());

                      
                        iPrinter.drawTextTSPL(18 * 8, 32 * 8, 40 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getUnit());

                        // 二维码下方的一维条码 13位
                        // 14,15,16,17,18 no 12
                     
                        iPrinter.drawTextTSPL(12 * 8, 37 * 8 + 2, 70 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, p.getSn());

                        //int start_x, int start_y, PBarcodeType type, int height, boolean isReadable, PRotate rotate, int narrowWidth, int wideWidth, String content
                        iPrinter.drawBarCodeTSPL(40, 40 * 8 + 4, PBarcodeType.JAN3_EAN13, 5 * 8, false, null, 1, 1, p.getSn());
                      
                        iPrinter.drawTextTSPL(65 * 8, 47 * 8, 80 * 8, 7 * 8, PAlign.START, PAlign.START, true, 1, 1, null, "物价员");
                    }
                    // 判断是否响应蜂鸣器
                    if (isBeep == 1) {
                        // 打印前响
                        iPrinter.beepTSPL(1, 1000);
                        Thread.sleep(3000);
                        // 打印
                        iPrinter.printTSPL(numbers, 1);
                    } else if (isBeep == 2) {
                        // 打印
                        iPrinter.printTSPL(numbers, 1);
                        // 打印后响
                        iPrinter.beepTSPL(1, 1000);
                    } else {
                        // 打印
                        iPrinter.printTSPL(numbers, 1);
                    }

                } catch (WriteException e) {
                    e.printStackTrace();
                } catch (PrinterPortNullException e) {
                    e.printStackTrace();
                } catch (ParameterErrorException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }
}
 

七、打印格式设置

 

import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.Time;

/**
 * SharePreference封装
 * 
 * @author Kevin
 * 
 */
public class PrefUtils {

   public static final String PREF_NAME = "config";

   public static boolean getBoolean(Context ctx, String key, boolean defaultValue) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      return sp.getBoolean(key, defaultValue);
   }

   public static void setBoolean(Context ctx, String key, boolean value) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      sp.edit().putBoolean(key, value).commit();
   }

   public static String getString(Context ctx, String key, String defaultValue) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      return sp.getString(key, defaultValue);
   }

   public static void setString(Context ctx, String key, String value) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      sp.edit().putString(key, value).commit();
   }

   public static int getInt(Context ctx, String key, int defaultValue) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      return sp.getInt(key, defaultValue);
   }

   public static void setInt(Context ctx, String key, int value) {
      SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
      sp.edit().putInt(key, value).commit();
   }

   public static String getSystemTime() {
      // or Time t=new Time("GMT+8"); 加上Time Zone资料。
      Time t = new Time();
      // 取得系统时间。
      t.setToNow();
      int year = t.year;
      int month = t.month + 1;
      int date = t.monthDay;
      // 0-23
      int hour = t.hour;
      int minute = t.minute;
      int seconds = t.second;
      String tag = "AM";
      if (hour >= 12) {
         tag = "PM";
      }
      String time = date + "/" + month + "/" + year + " " + hour + ":" + minute + " " + tag;
      return time;
   }

   public static String getSystemTime2() {
      // or Time t=new Time("GMT+8"); 加上Time Zone资料。
      Time t = new Time();
      // 取得系统时间。
      t.setToNow();
      int year = t.year;
      int month = t.month + 1;
      int date = t.monthDay;
      // 0-23
      int hour = t.hour;
      int minute = t.minute;
      int seconds = t.second;
      String tag = "AM";
      if (hour >= 12) {
         tag = "PM";
      }
      String time;
      if (month < 10) {
         if (seconds >= 10) {
            time = year + "-0" + month + "-" + date + "     " + hour + ":" + minute + ":" + seconds;
         } else {
            time = year + "-0" + month + "-" + date + "     " + hour + ":" + minute + ":0" + seconds;
         }

      } else {
         if (seconds >= 10) {
            time = year + "-" + month + "-" + date + "     " + hour + ":" + minute + ":" + seconds;
         } else {
            time = year + "-" + month + "-" + date + "     " + hour + ":" + minute + ":0" + seconds;
         }

      }
      return time;
   }

   public static String getSystemTime3() {
      // or Time t=new Time("GMT+8"); 加上Time Zone资料。
      Time t = new Time();
      // 取得系统时间。
      t.setToNow();
      int year = t.year;
      int month = t.month + 1;
      int date = t.monthDay;
      // 0-23
      int hour = t.hour;
      int minute = t.minute;
      int seconds = t.second;
      String tag = "AM";
      if (hour >= 12) {
         tag = "PM";
      }
      String time;
      if (month < 10) {
         if (seconds >= 10) {
            time = year + "-0" + month + "-" + date;
         } else {
            time = year + "-0" + month + "-" + date;
         }

      } else {
         if (seconds >= 10) {
            time = year + "-" + month + "-" + date;
         } else {
            time = year + "-" + month + "-" + date;
         }

      }
      return time;
   }
}
 

最后,直接贴上全部代码,代码是写在一个fragment里面去点击按钮去连接的,如需写在activity中去连接,可参考点击事件的监听方法里面的步骤去实现,同样的原理。代码如下:

 

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.usb.USBPort;
import com.printer.sdk.utils.XLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;


/**
 * 设置 - 标签
 *
 */

public class SettingLabelPrinterFragment extends SupportFragment implements View.OnClickListener {

    public static final int CONNECT_DEVICE = 1;

    protected static final String TAG = "SettingActivity";

    //    public PrinterInstance myPrinter;
    //这是默认是usb
    private int interfaceType = 1;

//    public String devicesName = "未知设备";

    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

    private static TextView tv_device_name;

    private RelativeLayout rl_print_connect;

    private RelativeLayout rl_print_test;

    private Button btn_connect;

    private Button btn_selfprint_test;
    //private static UsbDevice mUSBDevice //建议去掉静态
//    private UsbDevice mUSBDevice;

    private IntentFilter bluDisconnectFilter;
    // 打印机连接状态
//    public boolean isConnected = false;

    private RelativeLayout examine_print_state, off_print;
    public static TextView label_print_state;
    private Switch sw_front_reverse_printer;
    private TextView direction_select;
    private static Context mContext;
    private boolean direction;
    private SpannableString spannableString;
    public static PrinterInstance myPrinter;
    private static UsbDevice mUSBDevice;
    private static List<UsbDevice> deviceList;
    private static String deviceArrayLisr;
    public static String devicesName = "未知设备";
    private static String devicesAddress;
    // 打印机连接状态
    public static boolean isConnected = false;
    private static boolean hasRegDisconnectReceiver = false;
    private String strStatus = null;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting_label_printer, container, false);

        init(view);

        return view;
    }


    private void init(View view) {

        tv_device_name = (TextView) view.findViewById(R.id.tv_device_name);

        btn_connect = (Button) view.findViewById(R.id.btn_connect);

        btn_selfprint_test = (Button) view.findViewById(R.id.btn_selfprint_test);

        rl_print_connect = (RelativeLayout) view.findViewById(R.id.rl_print_connect);

        rl_print_test = (RelativeLayout) view.findViewById(R.id.rl_print_test);

        examine_print_state = view.findViewById(R.id.examine_print_state);//检查打印机状态

        off_print = view.findViewById(R.id.off_print);//断开打印机连接

        label_print_state = view.findViewById(R.id.label_print_state);//显示打印机状态

        sw_front_reverse_printer = view.findViewById(R.id.sw_front_reverse_printer);
        direction_select = view.findViewById(R.id.btn_direction_select);

        mContext = getActivity();
        examine_print_state.setOnClickListener(this);//检查打印机状态
        off_print.setOnClickListener(this);//断开打印机连接

        btn_connect.setOnClickListener(this);
        btn_selfprint_test.setOnClickListener(this);
        rl_print_connect.setOnClickListener(this);
        rl_print_test.setOnClickListener(this);


        if (null != ACache.get(getContext().getApplicationContext()).getAsObject(Constants.PRINT_DIRECTION)) {
            direction = (boolean) ACache.get(getContext().getApplicationContext()).getAsObject(Constants.PRINT_DIRECTION);
            Log.e("cai", "缓存状态:" + direction);
        } else {
            ACache.get(mContext.getApplicationContext()).put(Constants.PRINT_DIRECTION, false);
        }

        String str_direction = direction_select.getText().toString();
        spannableString = new SpannableString(str_direction);
        Log.e("cai", spannableString.toString());


        sw_front_reverse_printer.setChecked(direction);
        if (direction) {


            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorGrayText)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            direction_select.setText(spannableString);
            direction_select.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorGrayText)), 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            direction_select.setText(spannableString);
            direction_select.setMovementMethod(LinkMovementMethod.getInstance());
        }

        sw_front_reverse_printer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.e("cai", "+++" + isChecked);
                if (isChecked) {
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorGrayText)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    direction_select.setText(spannableString);
                    direction_select.setMovementMethod(LinkMovementMethod.getInstance());
                } else {
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorGrayText)), 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    direction_select.setText(spannableString);
                    direction_select.setMovementMethod(LinkMovementMethod.getInstance());
                }
                //保存打印正反方向状态数据到缓存
                ACache.get(mContext.getApplicationContext()).put(Constants.PRINT_DIRECTION, isChecked);
                updateButtonState(isConnected);
            }
        });
    }


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

    public void onStart() {
        super.onStart();
        updateButtonState(isConnected);
        Log.e("freak", "isConnected" + isConnected);
        Log.e("freak", "onStart");
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.rl_print_connect:
                //连接打印机
            case R.id.btn_connect:
//                showSelectDevicesDialog();
                getDevice();
                break;
            case R.id.off_print://断开打印机连接
                breakPrinter();
                break;
            case R.id.examine_print_state://检查打印机状态


                Log.e("freak", "isConnected==" + isConnected);
                if (isConnected) {

                    new Thread(new Runnable() {
                        public void run() {
                            int i = myPrinter.getCurrentStatus();
                            if (i == 0) {
                                strStatus = "打印机状态正常";
                            } else if (i == -1) {
                                strStatus = "接收数据失败";
                            } else if (i == -2) {
                                strStatus = "打印机缺纸";
                            } else if (i == -3) {
                                strStatus = "打印机纸将尽";
                            } else if (i == -4) {
                                strStatus = "打印机开盖";
                            } else if (i == -5) {
                                strStatus = "发送数据失败";
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                public void run() {
                                    ToastUtil.shortShow(strStatus);
                                    XLog.i(TAG, "zl at SettingActivity.java onClick()------> btn_status_test");
                                }
                            });

                        }

                    }).start();
                } else {
                    ToastUtil.shortShow(mContext.getResources().getString(R.string.no_connected));
                }
                break;
            case R.id.rl_print_test:
                //打印测试
            case R.id.btn_selfprint_test:

                if (!isConnected) {
                    ToastUtil.shortShow("设备未连接,请重连");
                    break;
                }

                ProductLabelBean productLabelBean = new ProductLabelBean();
                productLabelBean.setName("测试");
                productLabelBean.setUnit("包");
                productLabelBean.setCash("2.00");
                productLabelBean.setEprice("1");
                productLabelBean.setProducer("广州");
                productLabelBean.setSn("0000000000001");
                productLabelBean.setPrice("3.00");

                new PrintLabelGaomi().doPrintTSPL(myPrinter, getActivity(), productLabelBean);

                break;

            default:
                break;

        }

    }

    /**
     * 断开连接
     */
    public static void breakPrinter() {
        if (myPrinter != null) {
            /**
             * 断开打印设备的连接
             */
            myPrinter.closeConnection();
            myPrinter = null;//清空打印对象
            XLog.i(TAG, "yxz at SettingActivity.java  onClick()  mPrinter:" + myPrinter);
        }
        if (isConnected) {
            tv_device_name.setText("设备名称: " + "思普瑞特价签机");
            label_print_state.setText(mContext.getResources().getString(R.string.on_line));
        } else {
            tv_device_name.setText("设备名称:未连接");
            label_print_state.setText(mContext.getResources().getString(R.string.off_line));
        }
//    label_print_state.setText(mContext.getResources().getString(R.string.off_line));
        ToastUtil.shortShow("已断开连接");
    }

    public static void getDevice() {
        if (myPrinter == null) {
            /**
             * 检测所有的打印设备
             */
            UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);//获取usb权限
            HashMap<String, UsbDevice> devices = manager.getDeviceList();
            deviceList = new ArrayList<>();
            for (UsbDevice device : devices.values()) {
                /**
                 * 判断是都是打印设备。目前支持 (1155 != vendorId || 22304 != productId) && (1659 != vendorId || 8965 != productId) 两种
                 */
                if (USBPort.isUsbPrinter(device)) {
                    if (device.getVendorId() == 1155 && device.getProductId() == 22304) {
                        deviceArrayLisr = device.getDeviceName() + "\nvid: "
                                + device.getVendorId() + " pid: "
                                + device.getProductId();
                        deviceList.add(device);
                    }

                }
            }


            if (deviceList.isEmpty()) {
                ToastUtil.shortShow(mContext.getResources().getString(R.string.no_connected));
                return;
            }
            mUSBDevice = deviceList.get(0);
            if (mUSBDevice == null) {
                mHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
                return;
            }
            myPrinter = PrinterInstance.getPrinterInstance(mContext, mUSBDevice, mHandler);
            devicesName = mUSBDevice.getDeviceName();
            devicesAddress = "vid: " + mUSBDevice.getVendorId() + "  pid: " + mUSBDevice.getProductId();
            UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
            if (mUsbManager.hasPermission(mUSBDevice)) {
                myPrinter.openConnection();
            } else {
                // 没有权限询问用户是否授予权限
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                mContext.registerReceiver(mUsbReceiver, filter);
                mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后,系统弹出一个对话框
            }

        }

    }


    //弹出选择设备dialog
    private void showSelectDevicesDialog() {

        Intent intent = new Intent(getActivity(), UsbDeviceList.class);
        startActivityForResult(intent, CONNECT_DEVICE);
    }


    // 用于接受连接状态消息的 Handler
    @SuppressLint("HandlerLeak")
    public static Handler mHandler = new Handler() {
        @SuppressLint("ShowToast")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case PrinterConstants.Connect.SUCCESS:

                    ToastUtil.shortShow("连接成功");

                    isConnected = true;
                    Constants.ISCONNECTED = isConnected;
                    Constants.DEVICE_NAME = devicesName;
                    break;

                case PrinterConstants.Connect.FAILED:
                    isConnected = false;
                    ToastUtil.shortShow(mContext.getResources().getString(R.string.conn_failed));
                    Log.i(TAG, "连接失败!");
                    break;

                case PrinterConstants.Connect.CLOSED:
                    isConnected = false;
                    Constants.ISCONNECTED = isConnected;
                    Constants.DEVICE_NAME = devicesName;
                    Log.i(TAG, "连接关闭!");
                    break;
                case PrinterConstants.Connect.NODEVICE:
                    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);

        // TODO: 2017/12/5 禁用视频
//        MediaPlayer player = new MediaPlayer().create(mContext, R.raw.test2);
//        player.start();
    }


    private static void updateButtonState(boolean isConnected) {
        if (isConnected) {
            tv_device_name.setText("设备名称: " + "思普瑞特价签机");
            label_print_state.setText(mContext.getResources().getString(R.string.on_line));
//            getDevice();
        } else {
            label_print_state.setText(mContext.getResources().getString(R.string.off_line));
            tv_device_name.setText("设备名称:未连接");
            XLog.d(TAG, "yxz at SettingActivity.java updateButtonState() ---end");

        }
        PrefUtils.setBoolean(mContext, Constants.CONNECTSTATE, isConnected);
    }


    // 安卓3.1以后才有权限操作USB
    @SuppressLint("ShowToast")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == CONNECT_DEVICE) {
            // 连接设备
            // usb
            mUSBDevice = data.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            myPrinter = PrinterInstance.getPrinterInstance(getActivity(), mUSBDevice, mHandler);
            devicesName = "思普瑞特价签机";
            UsbManager mUsbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
            if (mUsbManager.hasPermission(mUSBDevice)) {
                myPrinter.openConnection();
            } else {
                // 没有权限询问用户是否授予权限
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0,
                        new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                getActivity().registerReceiver(mUsbReceiver, filter);
                // 该代码执行后,系统弹出一个对话框
                mUsbManager.requestPermission(mUSBDevice, pendingIntent);
            }

        }

    }

    private static final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        @SuppressLint("NewApi")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.w(TAG, "receiver action: " + action);

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    mContext.unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUSBDevice.equals(device)) {
                        myPrinter.openConnection();
                    } else {
                        mHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
                        Log.e(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    public void onDestroy() {
        XLog.e(TAG, "yxz at SettingActivity.java onDestroy()   progressdialog");
        super.onDestroy();
        if (hasRegDisconnectReceiver) {
            mContext.unregisterReceiver(mUsbReceiver);
            hasRegDisconnectReceiver = false;
            // Log.i(TAG, "关闭了广播!");
        }
    }

}
 

注:此连接方式是需要连接sdk去连接的,如遇到同样问题的开发朋友,可留言跟我要下载地址

附:标签打印的位置如果是正常位置的话,可根据xy的坐标去调试即可,但是如果标签是反过来了,就需要代码控制字体旋转180度,但是旋转之后的位置是需要注意的,旋转之后的字体如果超出了标签纸大小的话,就会出现打印异常,标签打印机不会打印,会没有反应,所有要算好位置。还有一个,就是标签打印机是不能打印null数据的,如果数据为null,则需要判空,如果为null,可以打印一个空格。

旋转180度方法经验总结:旋转180度,是以标签打印纸的中心,进行旋转,旋转位置就如长方形的对角位置互换,只是两个对角,就好比一根棍子放在中心点上去旋转180度一样,这是我调试总结出来的,希望对需要的开发的朋友提供些许帮助。尽早脱坑。如果发现了更好的办法,希望多多留意交流。

标签打印机下载地址:https://download.csdn.net/download/freak_csh/10836218

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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 20
    评论
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值