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

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")@Overridepublic 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() {@Overridepublic 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//45iPrinter.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.99if (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//snif (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 12if (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 contentiPrinter.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() {@Overridepublic 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 * 8iPrinter.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.99iPrinter.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 12iPrinter.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 contentiPrinter.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 12iPrinter.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 contentiPrinter.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-23int 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-23int 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-23int 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;//这是默认是usbprivate 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;@Overridepublic 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() {@Overridepublic 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);}});}@Overridepublic void onResume() {super.onResume();}public void onStart() {super.onStart();updateButtonState(isConnected);Log.e("freak", "isConnected" + isConnected);Log.e("freak", "onStart");}@Overridepublic 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); // 该代码执行后,系统弹出一个对话框}}}//弹出选择设备dialogprivate void showSelectDevicesDialog() {Intent intent = new Intent(getActivity(), UsbDeviceList.class);startActivityForResult(intent, CONNECT_DEVICE);}// 用于接受连接状态消息的 Handler@SuppressLint("HandlerLeak")public static Handler mHandler = new Handler() {@SuppressLint("ShowToast")@Overridepublic 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")@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode != Activity.RESULT_OK) {return;}if (requestCode == CONNECT_DEVICE) {// 连接设备// usbmUSBDevice = 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

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

  1. 斑马标签打印机蛋疼的打印错误处理方法

    斑马标签打印机蛋疼的打印错误处理方法 默认自动检测的纸张,打印预览的时候没有问题,但是打印出来的效果,就一小块,打印不全.这个蛋疼的问题,可能和操作系统有关系,win10打印的时候没有问题,win7就 ...

  2. 喵喵机打印机各系列通过USB数据线连接电脑打印

    前言 楼主买这个,其实是为了日常打印一下便贴,或者打印一下需要背诵的东西,打印一些创意.一开始买的是P3,发现不支持电脑打印,本人又懒得连手机打印,所以换成C1S. 各机型对比 从上面可以看到,D1, ...

  3. Android 蓝牙连接打印机打印网络图片

    实现蓝牙连接打印机打印网络图片 经过自己一下午加一个小时的时间整理出来,希望能帮助到各位码兄弟! 主要分为以下几步: 将网络图片URL转为bitmap :其中需要进行网络请求,不可在主线程中进行,需另 ...

  4. 更改android AVD模拟器创建路径位置的方法

    2019独角兽企业重金招聘Python工程师标准>>> 使用eclipse创建的android AVD模拟器,默认位置一般在用户文件夹下的.android文件夹中,并且路径不可有中文 ...

  5. STM32CubeMx + LWIP(实现UDP组播/MQTT/热插拔)系列 四 ----- MQTT的连接与使用

    mqtt的全局变量 mqtt_client_t *lwip_mqtt; mqtt的连接,不要直接复制粘贴哦,记得把参数设置成你项目中用到的数据 char LWIP_Connect(mqtt_clien ...

  6. Android真机调试打印日志的方法

    使用模拟器效率是很低的,所以真机调试是多数开发者的选择.使用模拟器调试程序和使用真机调试程序还是有一些不同的.比如,某些手机在调试过程中,不会打印日志出来. 真机调试不输出日志到logcat的原因是手 ...

  7. Win10下更改Android AVD 模拟器的存放位置的方法

    背景: 正常情况下Android AVD模拟器默认路径为c:\user\用户名.android\avd,当C盘空间远远不够时,我们需要欲将其移植到其他盘下,下面以D盘为例. 一.建立文件夹 在D盘下建 ...

  8. 四个修改Docker默认存储位置的方法

    参考:http://www.mamicode.com/info-detail-1917569.html 我使用方法二.修改镜像和容器的存放路径 指定镜像和容器存放路径的参数是--graph=/var/ ...

  9. Cadence OrCAD Capture 四种定位到图纸指定位置的方法说明

      

最新文章

  1. Ajax的异步,是鸡肋还是鸡排?
  2. java数组螺旋矩阵从上到下_Java-基础编程(螺旋矩阵乘法表)
  3. ZOJ1101-赌徒【二分查找】
  4. DFS应用——找出无向图的割点
  5. julia在mac环境变量_在Julia中找到值/变量的类型
  6. .net2.0 C# Json反序列化
  7. CSS 兼容浏览器的方法 CSS Hack
  8. 计算机组装错题整理,数学排列组合部分错题精选.docx
  9. 不靠运气靠实力 BEA全球大会千元门票免费送
  10. java判断光标位置_Java如何知道光标的当前位置?
  11. 链表相关的面试题型总结
  12. ubuntu虚拟机启动失败黑屏解决方案及原因
  13. python爬虫代码大作业_爬虫大作业
  14. Android Studio 问题:improperly specified vm option
  15. BUU-0CTFpiapiapia(反序列化字符串逃逸)
  16. 虚拟机Vmware打开vmx步骤
  17. 【Hexo】选择更高级的Markdown渲染器
  18. ipad微信已连接服务器失败,云旗舰云非凡千纸鹤微信安全提醒怎么办,你的微信账号通过ipad副设备发表失败...
  19. alibaba的druid连接池的监控的两种方法
  20. 灰色预测模型MATLAB代码及使用

热门文章

  1. 100天精通Oracle-实战系列 - 总目录
  2. 山东武术与宋太祖长拳
  3. 3d激光slam:LIO-SAM框架---特征点提取
  4. 一、JNI_OnLoad简介
  5. macbook鼠标与windows上下相反问题
  6. matlab和自然语言处理,《自然语言处理》课程简介
  7. 面试应答有哪些话术和技巧?
  8. 达芬奇调色,代理剪辑文件生成测试
  9. 如何在应用中跳转到 设置系统锁屏的界面
  10. Java:找出100以内的质数(一)。