package com.icod.yk_printer_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.icod.serial.SerialPortFinder;
import com.icod.yk_printer_test.OpenFileDialog.CallbackBundle;
import com.icod.yk_printer_test.utils.PrintParamManager;
import com.icod.yk_printer_test.utils.UIUtils;
import com.szsicod.print.escpos.PrinterAPI;
import com.szsicod.print.io.BluetoothAPI;
import com.szsicod.print.io.InterfaceAPI;
import com.szsicod.print.io.SerialAPI;
import com.szsicod.print.io.SocketAPI;
import com.szsicod.print.io.USBAPI;
import com.szsicod.print.io.UsbNativeAPI;
import com.szsicod.print.log.Logger;
import com.szsicod.print.utils.BitmapUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity implements PrinterAPI.FirmwareListener {
    private static final int STATUS = 3;

    static {
        //如果使用UsbNativeAPI 必须加载 适用root板 这个不需要权限窗口和申请权限
        System.loadLibrary("usb1.0");
        //串口
        System.loadLibrary("serial_icod");
        //图片
        System.loadLibrary("image_icod");
    }

    private String[] connect_type_string = {"USB", "bluetooth", "serial",
            "wifi", "usbNative"};
    private String[] baud_rate_string = UIUtils.getStringArr(R.array.baud_rate_string);
    private int[] baud_rate_int = UIUtils.getIntegerArr(R.array.baud_rate);
    private String[] speed = UIUtils.getStringArr(R.array.speed);
    private String[] pinStrings = UIUtils.getStringArr(R.array.pin);
    public PrinterAPI mPrinter = PrinterAPI.getInstance();
    private int REQUEST_CODE_PICK_IMAGE = 1;
    private ArrayList<String> mBTAddrList = new ArrayList<String>();
    private String[] mSerialportList = {"NONE"};
    private static Runnable runnable;
    private LinearLayout ll_ip;
    private EditText editTextText;
    private EditText editTextBarcode;
    private EditText editTextQRCode;
    private LinearLayout ll_root;
    private EditText edittext_ip;
    private EditText edittext_port;
    private EditText et_times;
    private EditText et_time;
    private boolean isPrintTextCut = false;
    private ImageView imageView;
    private Spinner spinnerConnectType;
    private Spinner spinnerBTDeviceList;
    private Spinner spinnerSpeed;
    private Spinner mSpPin;
    private Spinner spinnerBaudRate;
    private Button button_print_opencd;
    private Button buttoncConnect;
    private Button buttoncDisonnect;
    private Button buttoncPrintText;
    private Button btn_init_print;
    private Button buttoncPrintPos;
    private Button button_print_loop;
    private Button buttoncPrintBarcode;
    private Button buttoncPrintQRCode;
    private Button buttoncPrintBitmap;
    private Button button_getversion;
    private CheckBox cb_print_bitmap_check;
    private Button button_update;
    private Button button_cut;
    private Button button_page;
    private Button button_clear;
    private Button btnClearReceive;
    private Button button_cc;
    private Button button_print_58;
    private Button button_print_80;
    private Button button_print_left;
    private Button button_print_center;
    private Button button_print_right;
    private Button button_print_bb;
    private CheckBox cb_log;
    private CheckBox cbImage;
    private CheckBox cb_print_bitmap_cut;

    private Button buttonPrintColorSet;
    private EditText editTextColorSizeSet;
    private ProgressDialog progressDialog;
    private boolean cut_bitmap = false;
    private int serialFlowControl = 0;
    private static int openfileDialogId = 0;
    private Button btnTextHex;
    int iB;
    private Button btn_yaoqiu;
    private CheckBox cb_cut;
    private Button mBtnOpenCash;
    private Button btnAbout;
    private EditText etBarWidth;
    private CheckBox cb_barWidth;
    private boolean isSetBarHeight;
    private EditText etQRsize;
    private EditText etReceiver;
    private Button btnResetBd;
    private EditText etResetBd;
    private Spinner spBarSystem;
    private int barSystem;
    private final static int NO_CONNECT = 10;
    private final static int GETPRINTERVERSION = 101;
    private Spinner spflowcontrol;
    private int serialFlag = 0;
    private boolean statusFlag = false;
    private boolean isCheckConnect=true;
    private UsbBroadCastReceiver mUsbBroadCastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
        final String[] stringArr = UIUtils.getStringArr(R.array.barsystem);
        final ArrayAdapter barArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
                stringArr);
        spBarSystem = (Spinner) findViewById(R.id.sp_bar_system);
        spBarSystem.setAdapter(barArrayAdapter);
        spBarSystem.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String s = stringArr[position];
                String[] split = s.split(" ");
                barSystem = Integer.parseInt(split[1]);
                Log.i(TAG, "onItemSelected:barSystem " + barSystem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        final ArrayAdapter barArrayAdapterSpeed = new ArrayAdapter(this, android.R.layout
                .simple_list_item_1,
                speed);
        ((CheckBox)findViewById(R.id.check_connect)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheckConnect=isChecked;
            }
        });
        spinnerSpeed = (Spinner) findViewById(R.id.sp_sp_speed);
        spinnerSpeed.setAdapter(barArrayAdapterSpeed);
        findViewById(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        int selectedItemPosition = spinnerSpeed.getSelectedItemPosition();
                        int i = Integer.parseInt(speed[selectedItemPosition]);
                        mPrinter.hexMsg("##1d 45 " + i + "##", true);
                    }
                };
                new Thread(runnable).start();
            }
        });
        btnResetBd = (Button) findViewById(R.id.button_print_bd);
        etResetBd = (EditText) findViewById(R.id.edit_bd_size);
        btnResetBd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                progressRun();
                int anInt = 9600;
                try {

                    anInt = Integer.parseInt(etResetBd.getText().toString());
                } catch (Exception e) {
                    handler.sendEmptyMessage(PrinterAPI.ERR_PARAM);
                    return;
                }
                final int finalAnInt = anInt;
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (PrinterAPI.SUCCESS == mPrinter.changeBd(finalAnInt)) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(-1);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.button_print_symbol).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        mPrinter.setInterCharSet(8);
                        mPrinter.sendOrder(new byte[]{(byte) 0x5c});
                        mPrinter.setInterCharSet(0);
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.btn_demo_bill).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        startActivity(new Intent(MainActivity.this, BillActivity.class));
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.btn_fullCut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        mPrinter.fullCut();
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.btn_halfCut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        mPrinter.halfCut();
                    }
                };
                new Thread(runnable).start();
            }
        });
        button_cc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                progressRun();
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        if (PrinterAPI.SUCCESS == mPrinter.resetPrinter()) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.btn_nv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        InputStream inputStream =
                                null;
                        try {
                          /*  inputStream = getAssets().open("logo5.bmp");
                            Bitmap stream = BitmapFactory.decodeStream(inputStream);
*/
                            inputStream = getAssets().open("logo.bmp");
                            Bitmap stream1 = BitmapFactory.decodeStream(inputStream);

                            inputStream = getAssets().open("qrcode.bmp");
                            Bitmap stream2 = BitmapFactory.decodeStream(inputStream);
                            Bitmap bit[] = {stream1, stream2};
                            //定义位图 会存储到打印机中 一次就够了,再次直接传打印指令就行了
                            mPrinter.downLoadNvBitmap(bit);
                            //打印 位图
                            SystemClock.sleep(1000);
                            mPrinter.hexMsg("##1c 70 01 00 1c 70 02 00##", true);
                        } catch (IOException e) {

                            e.printStackTrace();
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
        final String[] strFlow = UIUtils.getStringArr(R.array.serialFlow);
        final ArrayAdapter serialAdater = new ArrayAdapter(this, android.R.layout
                .simple_spinner_item,
                strFlow);
        spflowcontrol = (Spinner) findViewById(R.id.sp_flowcontrol);
        spflowcontrol.setAdapter(serialAdater);
        spflowcontrol.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String s = strFlow[position];
                String[] split = s.split(" ");
                serialFlag = Integer.parseInt(split[1]);
                Log.i(TAG, "onItemSelected:serialFlag " + serialFlag);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        setListener();
        findViewById(R.id.button_zxing).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用zxing 库
                if (!isConnect()) return;
                startActivity(new Intent(MainActivity.this, ZxingActivity.class));
            }
        });
        findViewById(R.id.btn_point).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用zxing 库
                if (!isConnect()) return;
                mPrinter.setCharCodeTable(19);
                mPrinter.sendOrder(new byte[]{0x1c,0x2e});
                for (int i = 80; i < 0xff; i++) {
                    mPrinter.sendOrder(new byte[]{(byte) i});

                }
//恢复
                mPrinter.setCharCodeTable(0);
                mPrinter.sendOrder(new byte[]{0x1c,0x26});

            }
        });
        findViewById(R.id.btn_state_loop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用zxing 库
                if (!isConnect()) return;
                    String m="\n";
                try {
                    PrinterAPI.getInstance().printString(m);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
              /*  runnable=new Runnable() {
                    @Override
                    public void run() {
                        byte data[]=new byte[]{16,4,4};
                        byte readData[]=new byte[1];
                      int loop=0;
                       long num=0;
                        while (true){
                            PrinterAPI.getInstance().sendOrder(data);
                            int i = PrinterAPI.getInstance().readIO(readData, 0, 1, 2000);
                                if (i>0){
                                    Logger.i("读取成功 ","loop  ",loop,"data ",readData[0]);

                                }else{
                                    Logger.i("读取失败  ","loop ",loop,"data ",readData[0]);

                                }
                            SystemClock.sleep(2000);
                                num++;
                                if (Integer.MAX_VALUE<=num){
                                    num=0;
                                    loop++;
                                }
                        }


                    }
                };
                new Thread(runnable).start();*/
            }
        });
        findViewById(R.id.button_set_page_mode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isConnect()) return;
                startActivity(new Intent(MainActivity.this, PageModeActivity.class));
            }
        });
        findViewById(R.id.button_dip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用 dip 设置
                if (!isConnect()) return;
                startActivity(new Intent(MainActivity.this, DipSetActivity.class));
            }
        });
        findViewById(R.id.iv_set).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用 dip 设置
                if (!isConnect()) return;
                startActivity(new Intent(MainActivity.this, SetParamActivity.class));
            }
        });
        findViewById(R.id.btn_speed_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用 海信速度测试
                if (!isConnect()) return;
                startActivity(new Intent(MainActivity.this, SpeedActivity.class));
            }
        });
        button_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.selfTestPage();//自检
            }
        });
        findViewById(R.id.button_comeInHex).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.comeInHex();//进入十六进制
            }
        });

        findViewById(R.id.btn_print_6text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        // String string = UIUtils.getString(R.string.print_80);
                        String
                                tempData = "曾经也会有许多种想法，想要学习李白，想要成为张小娴，想着也许会阳光明媚的过这一生，可惜，那时候年轻到连想法都天马行空，这一辈子太久了，久到80集的电视连续剧都播放不完，又怎么做到像李白一样满腹经纶，又怎么成为张小娴一样看透所有的爱情。所以，这20多年以来，还是依然在车水马龙人潮拥挤的城市里浮沉。";
                        StringBuffer stringBuffer = new StringBuffer();
                        int length = tempData.length();
                        int num = 8000 / length;
                        for (int i = 0; i < num; i++) {
                            stringBuffer.append(tempData);
                        }
                        try {
                            mPrinter.sendOrder(stringBuffer.toString().getBytes("gbk"), 6000);//进入十六进制
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                };
                new Thread(runnable).start();

            }
        });
        findViewById(R.id.button_set_mark).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;//进入黑标设置
                startActivity(new Intent(MainActivity.this, MarkActivity.class));
            }
        });
        findViewById(R.id.btn_print_japan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;//
                mPrinter.sendOrder(new byte[]{0x1c,0x2e,0x1b,0x74,0x01});

                try {
                    //Logger.i(  Charset.availableCharsets().toString());
                    mPrinter.printString("ｹﾂｶﾝｶｿｳﾂｳ","Shift_JIS",false);
                    mPrinter.printAndFeedLine(10);
                    mPrinter.fullCut();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }finally {
                    mPrinter.setInterCharSet(0);
                    mPrinter.sendOrder(new byte[]{0x1c,0x26,0x1b,0x74,0x00});
                }

            }
        });

        mSpPin = (Spinner) findViewById(R.id.sp_pin);
        ArrayAdapter<String> pinAdapter = new ArrayAdapter<String>(this, android.R.layout
                .simple_spinner_item, pinStrings);
        mSpPin.setAdapter(pinAdapter);


    }

    private void setListener() {
        cbSelect();
        spinnerTypeInit();
        connectDevice();
        disconnectDevice();
        //initPrinter();
        printText();
        printTextLoop();
        printBitmap();
        printBarcode();
        printQRcode();
        sendHex();
        setAlignType();
        setColor();
        cutPage();
        getPrinterVersion();
        update();
        selectPageSize();
        clearText();
        openCashBox();
        getBaud();
        selectImagePrint();
        printTextAndHex();
        custom();
        about();
        btnClearReceive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etReceiver.setText("");
            }
        });
    }

    private void about() {
        btnAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Dialog dialog = new Dialog(MainActivity.this);
                dialog.setTitle(UIUtils.getString(R.string.version));
                View inflate = View.inflate(MainActivity.this, R.layout.dialog_about, null);
                dialog.setContentView(inflate);
                dialog.setCancelable(true);
                dialog.show();

            }
        });
    }

    //客户要求的打印格式
    private void custom() {
        btn_yaoqiu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;

                        String mess = etQRsize.getText().toString();
                        if ("".equals(mess) || null == mess) {
                            return;
                        }
                        //居中
                        mPrinter.setAlignMode(1);
                        //设置行距
                        mPrinter.setLineSpace(10);
                        //打印二维码
                        if (PrinterAPI.SUCCESS == mPrinter
                                .printQRCode(mess, 8, false)) {
                            mPrinter.printFeed();
                            // SystemClock.sleep(1000);
                            try {

                                if (PrinterAPI.SUCCESS == mPrinter.printString("121212121151515",
                                        "GBK", true)) {
                                    //换行n*行距
                                    mPrinter.printAndFeedLine(8);
                                    mPrinter.printString("测试测试测试测试测试" +
                                            "", "GBK", true);

                                    mPrinter.printString("1111111111", "GBK", true);

                                    SystemClock.sleep(500);

                                    mPrinter.printAndFeedLine(6);
                                    //设置字符的大小
                                    mPrinter.setCharSize(1, 0);
                                    mPrinter.printString("中国好青年是我，我是中国好青年", "GBK", false);
                                    mPrinter.cutPaper(66, 0);
                                    //恢复
                                    mPrinter.setDefaultLineSpace();
                                    mPrinter.setCharSize(0, 0);
                                }


                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    //打印文本和识别文本的十六进制,现在支持 文本+指令,指令+文本 ,指令+文本+指令,指令
    private void printTextAndHex() {
        btnTextHex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        try {
                            textHex(editTextText.getText().toString());
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            Log.i("log", "run: " + e.toString());
                        }
                    }
                }).start();
            }
        });
    }

    private void selectImagePrint() {
        imageView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!isConnect()) return;
                getImageFromAlbum();
            }
        });

    }

    private void getBaud() {
        button_print_bb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                runnable = new Runnable() {

                    @Override
                    public void run() {
                        InterfaceAPI io;
                        for (int i = 0; i < baud_rate_int.length; i++) {
                            //先选好路径
                            io = new SerialAPI(new File(
                                    mSerialportList[spinnerBTDeviceList
                                            .getSelectedItemPosition()]),
                                    baud_rate_int[i],
                                    serialFlowControl);

                            if (mPrinter.connect(io) == PrinterAPI.SUCCESS) {
                                iB = i;
                                handler.sendEmptyMessage(0x100);
                                break;
                            }
                        }

                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    private void openCashBox() {
        findViewById(R.id.btn_open_cash).setOnClickListener(new View
                .OnClickListener() {
            @Override
            public void onClick(View v) {
                //if (!isConnect())return;
                final int m = mSpPin.getSelectedItemPosition();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mPrinter.sendOrder(new byte[]{0x1b, 0x70, (byte) m, (byte) 0x10, (byte)
                                0xff,0x1b,0x40});
                    }
                }).start();
            }
        });
    }

    private void clearText() {
        button_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editTextText.setText("");
            }
        });

    }

    private void selectPageSize() {

        button_print_58.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.set58mm();
            }
        });

        button_print_80.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.set80mm();
            }
        });
    }

    private void update() {
        button_update.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!isConnect()) return;
                showDialog(openfileDialogId);

            }
        });

    }

    private void getPrinterVersion() {
        button_getversion.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

//				progressRun();
                runnable = new Runnable() {

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        String s = StatusDescribe.getStatusDescribe(mPrinter.getStatus());
                        Message message = Message.obtain(handler);
                        message.obj = s;
                        message.what = STATUS;
                        handler.sendMessage(message);
                        Logger.i("status" + s);
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.button_getPrintStatusByCtrl).setOnClickListener(new View.OnClickListener
                () {
            public void onClick(View v) {

//				progressRun();
                runnable = new Runnable() {

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        String s = StatusDescribe.getStatusDescribeWithControl(mPrinter.getStatusByControl());
                        Message message = Message.obtain(handler);
                        message.obj = s;
                        message.what = STATUS;
                        handler.sendMessage(message);
                        Logger.i("status" + s);
                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    private void cutPage() {
        button_cut.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                progressRun();
                runnable = new Runnable() {

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        if (PrinterAPI.SUCCESS == mPrinter.cutPaper(66, 0)) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }
                };
                new Thread(runnable).start();

            }
        });
    }

    private void printBitmap() {
        buttoncPrintBitmap.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (progressDialog!=null&&progressDialog.isShowing())return;
                progressRun();
                mPrinter.initAllPrinter(2);
                runnable = new Runnable() {

                    private Resources resources = getResources();

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        imageView.setDrawingCacheEnabled(true);
                        Bitmap drawingCache = imageView
                                .getDrawingCache();
                        Logger.i("width :", drawingCache.getWidth());
                        Logger.i("height :", drawingCache.getHeight());
                        if (mPrinter.getIO() instanceof BluetoothAPI) {
                            //蓝牙打印图片注意大小
                            drawingCache = BitmapUtils.reSizeByWidth(drawingCache, 380);
                            Logger.i("width :", drawingCache.getWidth());
                            Logger.i("height :", drawingCache.getHeight());
                        }
                        if (cut_bitmap) {
                            if (PrinterAPI.SUCCESS == cut(BitmapUtils.toGrays(drawingCache))) {
                                handler.sendEmptyMessage(0);
                            } else {
                                handler.sendEmptyMessage(1);
                            }
                        } else {
                            try {
                                if (mPrinter.getIO() instanceof SerialAPI) {
                                    //不需要写超时处理
                                    ((SerialAPI) mPrinter.getIO()).setNeedOutTime(false);
                                }
                                long start = System.currentTimeMillis();
                                if (PrinterAPI.SUCCESS == mPrinter.printRasterBitmap
                                        (drawingCache, false, -1, cb_print_bitmap_check
                                                .isChecked())
                                        ) {
                                    long end = System.currentTimeMillis();
                                    Log.i(TAG, "时间差 为:" + (end - start));
                                    Logger.i(StatusDescribe.getStatusDescribe(mPrinter.getStatus()));
                                    mPrinter.cutPaper(66, 10);
                                    handler.sendEmptyMessage(0);
                                } else {

                                    long end = System.currentTimeMillis();
                                    Log.i(TAG, "fail时间差 为:" + (end - start));
                                    imageView.setDrawingCacheEnabled(false);
                                    mPrinter.printFeed();
                                    //清楚打印缓存区 避免对后面数据的影响 有些设置会恢复默认值
                                    mPrinter.initAllPrinter(2);

                                    handler.sendEmptyMessage(-1);
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                };
                new Thread(runnable).start();

            }
        });
    }

    private void setColor() {
        buttonPrintColorSet.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                progressRun();
                runnable = new Runnable() {

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        if (TextUtils.isEmpty(editTextColorSizeSet.getText())) {
                            handler.sendEmptyMessage(1);
                        } else {
                            int num = 2;
                            try {
                                num = Integer.parseInt(editTextColorSizeSet.getText().toString());
                            } catch (Exception e) {
                            }

                            if (PrinterAPI.SUCCESS == mPrinter.setPrintColorSize(num)) {
                                handler.sendEmptyMessage(0);
                            } else {
                                handler.sendEmptyMessage(1);
                            }
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    private void setAlignType() {
        button_print_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.setAlignMode(0);
            }
        });

        button_print_center.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.setAlignMode(1);
            }
        });

        button_print_right.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                mPrinter.setAlignMode(2);
            }
        });
    }

    private void printQRcode() {
        buttoncPrintQRCode.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                progressRun();
                runnable = new Runnable() {
                    public void run() {
                        if (!isConnect()) return;
                        final String a = editTextQRCode.getText().toString();

                        String size = etQRsize.getText().toString().trim();
                        if ("".equals(size)) {
                            handler.sendEmptyMessage(PrinterAPI.ERR_PARAM);
                            return;
                        }
                        int i = 5;
                        try {

                            i = Integer.parseInt(size);
                        } catch (Exception e) {

                        }
                        if (PrinterAPI.SUCCESS == mPrinter
                                .printQRCode
                                        ("https://dsf.etcp.cn/sweepCodeRed/otherParkingfee", 6,
                                                false)) {
                            mPrinter.printFeed();
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    private void printBarcode() {
        buttoncPrintBarcode.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                progressRun();
                runnable = new Runnable() {

                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        String size = etBarWidth.getText().toString().trim();
                        if (!"".equals(size) && isSetBarHeight) {
                            try {
                                int num = Integer.parseInt(size);
                                mPrinter.setBarCodeWidth(num);
                            } catch (Exception e) {
                            }

                        } else {
                            mPrinter.setBarCodeWidth(2);
                        }
                        String mess = editTextBarcode.getText()
                                .toString();
                        try {
                            handler.sendEmptyMessage(mPrinter.printBarCode(barSystem, mess.length()
                                    , mess));

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                };
                new Thread(runnable).start();

            }
        });
    }

    private void printTextLoop() {
        button_print_loop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                final int times = Integer
                        .valueOf(et_times.getText().toString());
                final int time = Integer.valueOf(et_time.getText().toString());

                progressRun();
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        Bitmap bitmap = null;
                        Bitmap scaleBitmap = null;

                        try {
                            InputStream open = getAssets().open("maoyan.jpg");
                            bitmap = BitmapFactory.decodeStream(open);
                            Logger.i("width:", bitmap.getWidth());
                            if (PrintParamManager.getInstance().isIs58Printer()) {
                                if (bitmap.getWidth() > PrintParamManager.Print_58_width) {
                                    scaleBitmap = BitmapUtils.reSizeByWidth(bitmap,
                                            PrintParamManager.Print_58_width);
                                    Logger.i("五八");
                                }
                            } else {
                                if (bitmap.getWidth() > PrintParamManager.Print_80_width) {
                                    scaleBitmap = BitmapUtils.reSizeByWidth(bitmap,
                                            PrintParamManager.Print_80_width);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(PrinterAPI.FAIL);
                            return;
                        }
                        if (scaleBitmap == null) {
                            scaleBitmap = bitmap;
                        } else {
                            if (!bitmap.isRecycled()) {
                                bitmap.recycle();
                            }
                        }
                        // imageView.setDrawingCacheEnabled(true);
                        try {
                            imageView.setDrawingCacheEnabled(true);
                            for (int i = 0; i < times; i++) {
                                if (PrinterAPI.SUCCESS == (cbImage.isChecked() ? mPrinter
                                        .printRasterBitmap(imageView.getDrawingCache())
                                        : mPrinter
                                        .printString(
                                                editTextText.getText().toString(),
                                                "GBK", true))) {
                                    if (cb_cut.isChecked()) {
                                        mPrinter.cutPaper(66, 0);
                                        Thread.sleep(time);
                                    }
                                } else {
                                    handler.sendEmptyMessage(1);
                                }
                            }
                            handler.sendEmptyMessage(0);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(1);
                        } catch (IOException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(1);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    //发送十六进制指令
    private void sendHex() {
        buttoncPrintPos.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        mPrinter.hexMsg(editTextText.getText().toString(), true);
                    }
                };
                new Thread(runnable).start();
            }
        });

    }

    private void printText() {
        buttoncPrintText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (progressDialog!=null&&progressDialog.isShowing())return;
                if (!isConnect()) return;
                progressRun();
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //mPrinter.setAlignMode(1);
                            mPrinter.setFontStyle(0);
                            if (PrinterAPI.SUCCESS == mPrinter.printString(
                                    editTextText.getText().toString(), "GBK", true)) {
                                if (isPrintTextCut) {
                                    try {
                                        Thread.sleep(100);
                                        mPrinter.cutPaper(66, 0);

                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }

                                handler.sendEmptyMessage(0);
                            } else {
                                handler.sendEmptyMessage(1);
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
    }

    /*private void initPrinter() {
        btn_init_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mPrinter.init_print();
                        Log.i("log", "run: init_print");
                    }
                }).start();
            }
        });
    }*/

    private void disconnectDevice() {
        buttoncDisonnect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!isConnect()) return;
                if (PrinterAPI.SUCCESS == mPrinter.disconnect()) {
                    handler.sendEmptyMessage(0);
                } else {
                    handler.sendEmptyMessage(1);
                }
            }
        });
    }

    private void connectDevice() {
        buttoncConnect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // if opened you must call disconnet();
                if (mPrinter.isConnect()) {
                    mPrinter.disconnect();
                }

                progressRun();
                runnable = new Runnable() {
                    @Override
                    public void run() {


                        InterfaceAPI io = null;
                        if (0 == spinnerConnectType.getSelectedItemPosition()) {
                           if (mUsbBroadCastReceiver==null){
                            IntentFilter intentFilter=new IntentFilter();
                            intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                            intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                            mUsbBroadCastReceiver=new UsbBroadCastReceiver();
                            registerReceiver(mUsbBroadCastReceiver,intentFilter);}
                            io = new USBAPI(MainActivity.this);
                        } else if (1 == spinnerConnectType
                                .getSelectedItemPosition()) {
                            Intent intent = new Intent(MainActivity.this, BluetoothActivity.class);
                            startActivityForResult(intent, PrinterAPI.SUCCESS);

                            return;
                        } else if (2 == spinnerConnectType
                                .getSelectedItemPosition()) {

                            io = new SerialAPI(new File(
                                    mSerialportList[spinnerBTDeviceList
                                            .getSelectedItemPosition()]),
                                    baud_rate_int[spinnerBaudRate
                                            .getSelectedItemPosition()],
                                    serialFlag);
                        } else if (3 == spinnerConnectType
                                .getSelectedItemPosition()) {
                            if (edittext_ip.getText().toString().isEmpty()
                                    || edittext_port.getText().toString()
                                    .isEmpty()) {

                            } else {
                                String site = edittext_ip.getText().toString();
                                int port = Integer.valueOf(edittext_port
                                        .getText().toString());
                                io = new SocketAPI(site, port);

                            }

                        } else if (4 == spinnerConnectType.getSelectedItemPosition()) {
                            // if your Android mainboard have root permission you can usb this;


                            io = new UsbNativeAPI();
                        }
                        if (PrinterAPI.SUCCESS == mPrinter.connect(io)) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    //设备类型选择
    private void spinnerTypeInit() {
        spinnerBTDeviceList.setVisibility(View.INVISIBLE);

        ArrayAdapter<String> adapterTemp = null;
        adapterTemp = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, connect_type_string);
        adapterTemp
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerConnectType.setAdapter(adapterTemp);
        spinnerConnectType.setVisibility(View.VISIBLE);
        spinnerConnectType
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> adapter,
                                               View view, int position, long id) {
                        spflowcontrol.setVisibility(View.GONE);
                        String sInfo = adapter.getItemAtPosition(position)
                                .toString();

                        spinnerBaudRate.setVisibility(View.INVISIBLE);
                        spinnerBTDeviceList.setVisibility(View.INVISIBLE);
                        if (sInfo == connect_type_string[1]) {
                            ll_ip.setVisibility(View.GONE);
                            //  spinnerBTDeviceList.setVisibility(View.VISIBLE);
                            spflowcontrol.setVisibility(View.GONE);
                        } else if (sInfo == connect_type_string[0]) {
                            ll_ip.setVisibility(View.GONE);
                        } else if (sInfo == connect_type_string[2]) {
                            ll_ip.setVisibility(View.GONE);
                            spflowcontrol.setVisibility(View.VISIBLE);
                            SerialPortFinder spf = new SerialPortFinder();
                            mSerialportList = spf.getAllDevicesPath();
                            if (mSerialportList.length <= 0)
                                mSerialportList = new String[]{"NONE"};
                            ArrayAdapter<String> adapterTemp = null;
                            adapterTemp = new ArrayAdapter<String>(MainActivity.this,
                                    android.R.layout.simple_spinner_item,
                                    mSerialportList);
                            adapterTemp
                                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinnerBTDeviceList.setAdapter(adapterTemp);
                            spinnerBTDeviceList.setVisibility(View.VISIBLE);

                            ArrayAdapter<String> adapterTemp2 = new ArrayAdapter<String>(
                                    MainActivity.this,
                                    android.R.layout.simple_spinner_item,
                                    baud_rate_string);
                            adapterTemp2
                                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinnerBaudRate.setAdapter(adapterTemp2);
                            spinnerBaudRate.setVisibility(View.VISIBLE);
                        } else if (sInfo == connect_type_string[3]) {
                            ll_ip.setVisibility(View.VISIBLE);
                        }
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
    }

    //checkBox选择
    private void cbSelect() {
        cb_log.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (!isConnect()) return;
                mPrinter.setOutput(isChecked);

            }
        });
        cb_barWidth.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                isSetBarHeight = isChecked;
            }
        });
        cb_cut.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (!isConnect()) return;
                isPrintTextCut = isChecked;

            }
        });

        cb_print_bitmap_cut
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        if (!isConnect()) return;
                        cut_bitmap = isChecked;

                    }
                });
        findViewById(R.id.btn_haixin_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isConnect()) return;
                for (int i = 0; i < 10; i++) {

/*
                try {

                    PrinterAPI.getInstance().printString("_______小票______");
                    PrinterAPI.getInstance().printFeed();
                    PrinterAPI.getInstance().printFeed();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }*/
                PrinterAPI.getInstance().sendOrder(new byte[]{29,72,2});
                PrinterAPI.getInstance().printCode128("ABCD0123456789012345");
                }
            }
        });


    }

    private void findView() {
        ll_ip = (LinearLayout) findViewById(R.id.ll_ip);
        cb_cut = (CheckBox) findViewById(R.id.cb_cut);
        cb_log = (CheckBox) findViewById(R.id.cb_log);
        cbImage = (CheckBox) findViewById(R.id.cb_image);
        cb_print_bitmap_check = (CheckBox) findViewById(R.id.cb_print_bitmap_check);
        cb_print_bitmap_cut = (CheckBox) findViewById(R.id.cb_print_bitmap_cut);

        editTextText = (EditText) findViewById(R.id.et_send);
        editTextBarcode = (EditText) findViewById(R.id.edittext_barcode);
        editTextQRCode = (EditText) findViewById(R.id.edittext_qrcode);
        editTextColorSizeSet = (EditText) findViewById(R.id.edittext_color_size);
        edittext_ip = (EditText) findViewById(R.id.edittext_ip);
        edittext_port = (EditText) findViewById(R.id.edittext_port);
        et_times = (EditText) findViewById(R.id.et_times);
        et_time = (EditText) findViewById(R.id.et_time);
        imageView = (ImageView) findViewById(R.id.imageview_bitmap);
        spinnerConnectType = (Spinner) findViewById(R.id.spinner_connect_type);
        spinnerBTDeviceList = (Spinner) findViewById(R.id.spinner_bt_device_list);
        spinnerBaudRate = (Spinner) findViewById(R.id.spinner_baud_rate);
        buttoncConnect = (Button) findViewById(R.id.button_connect);
        buttoncDisonnect = (Button) findViewById(R.id.button_close);

        buttoncPrintText = (Button) findViewById(R.id.button_print_text);
        buttoncPrintPos = (Button) findViewById(R.id.button_print_pos);
        button_print_loop = (Button) findViewById(R.id.button_print_loop);
        buttoncPrintBarcode = (Button) findViewById(R.id.button_print_barcode);
        buttoncPrintQRCode = (Button) findViewById(R.id.button_print_qrcode);
        buttonPrintColorSet = (Button) findViewById(R.id.button_print_color);
        buttoncPrintBitmap = (Button) findViewById(R.id.button_print_bitmap);
        button_cut = (Button) findViewById(R.id.button_cut);
        button_getversion = (Button) findViewById(R.id.button_getPrintStatus);
        button_cc = (Button) findViewById(R.id.button_print_cc);
        button_update = (Button) findViewById(R.id.button_update);
        button_page = (Button) findViewById(R.id.button_page);
        button_print_58 = (Button) findViewById(R.id.button_print_58);
        button_print_80 = (Button) findViewById(R.id.button_print_80);
        button_print_left = (Button) findViewById(R.id.button_print_left);
        button_clear = (Button) findViewById(R.id.button_clear);
        button_print_center = (Button) findViewById(R.id.button_print_center);
        button_print_right = (Button) findViewById(R.id.button_print_right);

        button_print_bb = (Button) findViewById(R.id.button_print_bb);
        btnTextHex = (Button) findViewById(R.id.btn_text_hex);
        btn_yaoqiu = (Button) findViewById(R.id.btn_yaoqiu);
        btnClearReceive = (Button) findViewById(R.id.btn_clear_receive);
        btnAbout = (Button) findViewById(R.id.btn_about);
        etBarWidth = (EditText) findViewById(R.id.et_barWidth);
        etReceiver = (EditText) findViewById(R.id.et_receive);
        cb_barWidth = (CheckBox) findViewById(R.id.cb_barWidth);
        etQRsize = (EditText) findViewById(R.id.et_qr_size);
        findViewById(R.id.btn_getPrinterVersion).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        String printerVersion = mPrinter.getPrinterVersion();

                        Logger.i("当前版本是:" + printerVersion);
                        if (!"-1".equals(printerVersion)) {
                            Message obtain = Message.obtain();
                            obtain.what = GETPRINTERVERSION;
                            obtain.obj = printerVersion;
                            handler.sendMessage(obtain);
                        }
                    }
                };
                new Thread(runnable).start();
            }
        });
        findViewById(R.id.button_cut_status).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        // -1 为数据传输错误;0正常;1 卡纸
                        Logger.i("卡纸状态:" + mPrinter.getPrinterCutStatus());
                    }
                };
                new Thread(runnable).start();
            }
        });

        findViewById(R.id.btn_power).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isConnect()) return;
                        //打印机位图1
                        mPrinter.hexMsg("##1c 70 01 00##", true);
                        mPrinter.printFeed();
                        try {
                            mPrinter.setCharSize(1, 1);//设置字体大小
                            mPrinter.printString("办理票号 :");
                            mPrinter.printFeed();
                            mPrinter.printString("办理业务 :");
                            mPrinter.printFeed();
                            mPrinter.printString("办理窗口 :");
                            mPrinter.printFeed();
                            mPrinter.printString("等待人数 :");
                            mPrinter.printFeed();
                            mPrinter.printString("取号时间 :");
                            mPrinter.printFeed();
                            mPrinter.setCharSize(0, 0);//恢复字体大小
                            mPrinter.printString("上下午分开区号,过号请重新取号!");
                            mPrinter.printFeed();
                            mPrinter.printString("微信扫一扫二维码,即可关注南方电网,空中排队,预约省时省力,还可以查缴电费,更方便!");
                            mPrinter.printFeed();
                            //打印机位图2
                            mPrinter.setAlignMode(1);//居中
                            mPrinter.hexMsg("##1c 70 02 00##", true);
                            mPrinter.cutPaper(66, 0);
                            mPrinter.setAlignMode(0);//恢复
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new NoLeakHandler(MainActivity.this) {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case PrinterAPI.ERR_PARAM:

                    Toast.makeText(MainActivity.this, R.string.error_param,
                            Toast.LENGTH_SHORT).show();
                    break;
                case PrinterAPI.NOSUPPROT:

                    Toast.makeText(MainActivity.this, R.string.no_support,
                            Toast.LENGTH_SHORT).show();
                    break;
                case PrinterAPI.FAIL:

                    break;
                case PrinterAPI.SUCCESS:

                    Toast.makeText(MainActivity.this, R.string.func_success,
                            Toast.LENGTH_SHORT).show();
                    break;
                case PrinterAPI.STRINGLONG:

                    Toast.makeText(MainActivity.this, R.string.string_to_long,
                            Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    Toast.makeText(MainActivity.this, R.string.func_failed,
                            Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(MainActivity.this, "socket connect fail",
                            Toast.LENGTH_SHORT).show();
                    break;
                case STATUS:

                    etReceiver.setText("");
                    etReceiver.setText(UIUtils.getString(R.string.printerStatus) + (String) msg.obj);
                    break;
                case 0x100:
                    etReceiver.setText("");
                    etReceiver.setText(UIUtils.getString(R.string.currentPrintBaud) + baud_rate_string[iB]);

                    break;
                case NO_CONNECT:
                    etReceiver.setText("");
                    etReceiver.setText(R.string.no_connect);
                    Toast.makeText(MainActivity.this, R.string.no_connect,
                            Toast.LENGTH_SHORT).show();

                    break;
                case GETPRINTERVERSION:
                    etReceiver.setText("");
                    etReceiver.setText(msg.obj.toString());

                    break;

            }
            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.dismiss();// 销毁对话框

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        //scrollView.scrollTo(0,0);
        //解决大尺寸不能滑到顶部的问题
        ll_root = (LinearLayout) findViewById(R.id.ll_root);
        ll_root.setFocusable(true);
        ll_root.setFocusableInTouchMode(true);
        ll_root.requestFocus();
        //开始状态轮训 串口没有流控勿用
        // startState();
    }

    protected void getImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    final Intent data) {
        if (resultCode != 0 && requestCode == REQUEST_CODE_PICK_IMAGE&&data!=null) {
            Bitmap photoBmp = null;
            try {
            final Uri uri = data.getData();

            if (uri==null){
                UIUtils.showToast("url 为空");
                return;
            }

                photoBmp = MediaStore.Images.Media
                        .getBitmap(getContentResolver(), uri);

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
                Logger.e(e1.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
                Logger.e(e1.getMessage());
            }
            if (photoBmp==null){UIUtils.showToast("无法获取图片"); return;}
            final Bitmap b = BitmapUtils.toGrays(photoBmp);
            progressRun();
            runnable = new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Uri uri = data.getData();
                    // to do find the path of pic
                    if (uri.getPath() != "") {
                        try {
                            Bitmap photoBmp = MediaStore.Images.Media
                                    .getBitmap(getContentResolver(), uri);

                            final int times = Integer
                                    .valueOf(et_times.getText().toString());
                            final int time = Integer.valueOf(et_time.getText().toString());
                            photoBmp = BitmapUtils.toGrays(photoBmp);
                            for (int i = 0; i < times; i++) {
                                if (photoBmp != null) {
                                    if (cut_bitmap) {
                                        if (!(PrinterAPI.SUCCESS == cut(photoBmp)))
                                            handler.sendEmptyMessage(1);
                                        return;
                                    } else {
                                        try {
                                            if (mPrinter.getIO() instanceof SerialAPI) {
                                                //不需要写超时处理
                                                ((SerialAPI) mPrinter.getIO()).setNeedOutTime(false);
                                            }
                                         //   final Bitmap finalPhotoBmp = photoBmp;
                                          /*  runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    imageView.setImageBitmap(finalPhotoBmp);
                                                }
                                            });*/
                                            if (!(PrinterAPI.SUCCESS == mPrinter
                                                    .printRasterBitmap(photoBmp, false, 2000,
                                                           false, cb_print_bitmap_check.isChecked())
                                            )) {

                                                handler.sendEmptyMessage(1);
                                                return;
                                            }
                                        } catch (IOException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                SystemClock.sleep(time);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }finally {
                            handler.sendEmptyMessage(0);
                        }
                    }
                }
            };
            new Thread(runnable).start();

        } else if (resultCode == PrinterAPI.SUCCESS && requestCode == PrinterAPI.SUCCESS) {
            if (data != null) {
                String stringExtra = data.getStringExtra(BluetoothActivity.EXTRA_ADDRESS);
                if (stringExtra != null) {
                    spinnerBTDeviceList.setVisibility(View.VISIBLE);
                    ArrayAdapter<String> adapterTemp = null;
                    mBTAddrList.clear();
                    mBTAddrList.add(stringExtra);
                    adapterTemp = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item,
                            mBTAddrList);
                    adapterTemp
                            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerBTDeviceList.setAdapter(adapterTemp);
                    spinnerBTDeviceList.setVisibility(View.VISIBLE);
                }
            }
        }
    }


    // 40mm*8=320px
    public int cut(Bitmap bmp) {
        Bitmap bitmap = null;
        int height = 120;

        int avgHeight = bmp.getHeight() / height;

        int top = 0;
        if (bmp.getHeight() % height != 0) {
            avgHeight++;
        }
        for (int i = 0; i < avgHeight; i++) {
            if (top + height > bmp.getHeight())
                height = bmp.getHeight() - top;
            bitmap = Bitmap.createBitmap(bmp, 0, top, bmp.getWidth(), height);
            top = top + height;

            try {

                mPrinter.printRasterBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        return 0;
    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        if (id == openfileDialogId) {
            Map<String, Integer> images = new HashMap<String, Integer>();
            // 下面几句设置各文件类型的图标， 需要你先把图标添加到资源文件夹
            images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root); // 根目录图标
            images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up); // 返回上一层的图标
            images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder); // 文件夹图标
            images.put("bin", R.drawable.ic_launcher); // bin文件图标
            images.put(OpenFileDialog.sEmpty, R.drawable.filedialog_root);
            Dialog dialog = OpenFileDialog.createDialog(id, this, "open",
                    new CallbackBundle() {
                        @Override
                        public void callback(Bundle bundle) {
                            String filepath = bundle.getString("path");
                            firmwareUpdate(filepath);
                        }
                    }, ".bin;", images);
            return dialog;
        }
        return null;
    }

    private void progressRun() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle(R.string.print_posing);
        progressDialog.setMessage("Please waiting...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条对话框//样式（水平，旋转）
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void progressUpdate() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle(R.string.print_posing);
        progressDialog.setMessage("updating...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置进度条对话框//样式（水平，旋转）
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void firmwareUpdate(final String filepath) {
        mPrinter.setmFirmwareListener(this);
        progressUpdate();
        runnable = new Runnable() {
            @Override
            public void run() {

                File file = new File(filepath);
                if (mPrinter.updateFirmware(file) == 0) {
                    handler.sendEmptyMessage(0);
                } else {
                    handler.sendEmptyMessage(1);
                }
            }
        };
        new Thread(runnable).start();
    }


    public boolean textHex(String text) throws UnsupportedEncodingException {
        if (null == text || "".equals(text)) {
            return false;
        }
        String hex = "";
        text = text.trim();
        int length = text.length();
        Pattern pattern = Pattern.compile("\\#\\#+");
        Matcher matcher = pattern.matcher(text);
        int count = 0;
        ArrayList<Integer> position = new ArrayList<Integer>();
        while (matcher.find()) {
            count++;
            Log.i("log", "textHex1: start" + matcher.start());
            position.add(matcher.start());

        }
        if (count <= 1) {
            if (!"".equals(text)) {
                return mPrinter.printString(text, "GBK", false) == 0 ? true : false;
            }
        }
        if (length < 4) {
            return false;
        }
        if (position.size() == 2) {
            Integer start = position.get(0);
            Integer end = position.get(1);
            //文本+指令
            if (start > 0 && text.length() - 1 == end + 1) {
                String mess = text.substring(0, start);
                Log.i("log", "textHex1: " + mess);
                String cmd = text.substring(start, text.length());
                Log.i("log", "textHex1: " + cmd);
                if (mPrinter.printString(mess, "GBK", false) == PrinterAPI.SUCCESS) {
                    SystemClock.sleep(500);
                    mPrinter.hexMsg(cmd, true);
                    handler.sendEmptyMessage(0);
                } else {
                    handler.sendEmptyMessage(1);
                }
            }
            //只有指令
            if (start == 0 && text.length() - 1 == end + 1) {
                mPrinter.hexMsg(text, true);
                return true;
            }
            //指令+文本
            if (start == 0 && end + 1 < text.length() - 1) {
                String cmd = text.substring(0, end + 2);
                Log.i("log", "textHex1: " + cmd);
                String mess = text.substring(end + 2);
                if (mPrinter.hexMsg(cmd, true) == PrinterAPI.SUCCESS) {
                    SystemClock.sleep(500);
                    mPrinter.printString(mess, "GBK", false);
                    handler.sendEmptyMessage(0);
                } else {
                    handler.sendEmptyMessage(1);
                }
                Log.i("log", "textHex1: " + mess);
                return true;
            }
            //文本+指令+文本
            if (start > 0 && end + 1 < text.length() - 1) {
                String front_mess = text.substring(0, start);
                Log.i("log", "textHex1: " + front_mess);
                String cmd = text.substring(start, end + 2);
                String after_mess = text.substring(end + 2);
                Log.i("log", "textHex1: " + cmd);
                Log.i("log", "textHex1: " + after_mess);
                if (mPrinter.printString(front_mess, "GBK", false) == PrinterAPI.SUCCESS) {
                    SystemClock.sleep(500);
                    mPrinter.hexMsg(cmd, true);
                    if (!"".equals(after_mess)) {
                        SystemClock.sleep(500);
                        mPrinter.printString(after_mess, "GBK", false);
                    }
                    handler.sendEmptyMessage(0);
                } else {
                    handler.sendEmptyMessage(1);
                }
                return true;
            }

        }
        if (position.size() == 4) {
            String cmd = "";
            String mess = "";
            String cmd2 = "";
            String after_mess = "";
            if (position.get(3) + 1 == text.length() - 1) {
                cmd = text.substring(0, position.get(1) + 2);
                mess = text.substring(position.get(1) + 2, position.get(2));
                cmd2 = text.substring(position.get(2));
                // 指令+文本+指令+文本
            } else if (position.get(3) + 1 < text.length() - 1) {
                cmd = text.substring(0, position.get(1) + 2);
                mess = text.substring(position.get(1) + 2, position.get(2));
                cmd2 = text.substring(position.get(2), position.get(3) + 2);
                after_mess = text.substring(position.get(3) + 2);

            }
            if (mPrinter.hexMsg(cmd, true) == PrinterAPI.SUCCESS) {
                SystemClock.sleep(500);

                if (mPrinter.printString(mess, "GBK", false) == -1) {
                    return false;
                }

                if (!"".equals(cmd2)) {
                    SystemClock.sleep(500);
                    mPrinter.hexMsg(cmd2, true);
                }
                if (!"".equals(after_mess)) {
                    SystemClock.sleep(500);
                    if (mPrinter.printString(after_mess, "GBK", false) == -1) {
                        return false;
                    }
                }
                handler.sendEmptyMessage(0);
            } else {
                handler.sendEmptyMessage(1);
            }
            return true;
        }
        //不符规则 当做字符窜处理
        return mPrinter.printString(text, "GBK", false) == 0 ? true : false;
    }

    public boolean isConnect() {
        if (!isCheckConnect)return true;
        boolean isConnect = true;
        if (!mPrinter.isConnect()) {
            handler.sendEmptyMessage(NO_CONNECT);
            isConnect = false;
        }
        return isConnect;
    }

    @Override
    public void onFirmware(int progress, int code) {
        if (code == PrinterAPI.SUCCESS) {
            progressDialog.setProgress(progress);
            if (progress == 100) {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
            }
        } else if (code == PrinterAPI.FAIL) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "未能读取到数据", Toast.LENGTH_LONG).show();
                }
            });
        } else if (code == -2) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "校验失败", Toast.LENGTH_LONG).show();
                }
            });
        }
    }

    private static class NoLeakHandler extends Handler {
        WeakReference<MainActivity> wf = null;

        private NoLeakHandler(MainActivity activity) {
            wf = new WeakReference<MainActivity>(activity);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);

        if (mPrinter != null) {
            mPrinter.disconnect();
            mPrinter = null;
            Logger.i("资源已经关闭");
        }
        if (mUsbBroadCastReceiver!=null)
        unregisterReceiver(mUsbBroadCastReceiver);
        statusFlag = true;
    }

    public void startState() {

        Thread thread = new Thread(new StateThread());
        thread.start();

    }

    class StateThread implements Runnable {

        @Override
        public void run() {
            while (!statusFlag) {
                if (mPrinter.isConnect()) {
                    //参数为超时时间 ms 如果再这段时间内没有数据返回,说明正在打印 这个只对缺纸处理
                    int status = mPrinter.getStatusForPrinting(5);
                    if (status == 1) {
                        Logger.i("打印完成");

                    } else if (status == 2) {
                        Logger.i("缺纸");
                    } else if (status == 0) {
                        Logger.i("打印中");
                    } else {
                        Logger.i("数据传输错误");
                    }

                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }


    }
    //usb 监听 由于权限问题而且sdk内部有超时时间 ,适用情况应该是系统默认usb权限开放或者root 板则使用UsbNativeApi
    private class UsbBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Logger.i("action",action);
            if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                UsbDevice usbDevice=  intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (usbDevice!=null){
                    InterfaceAPI io = PrinterAPI.getInstance().getIO();
                    if (io instanceof USBAPI ||io instanceof  UsbNativeAPI){
                        PrinterAPI.getInstance().disconnect();
                        Toast.makeText(MainActivity.this,"断开连接",Toast.LENGTH_LONG).show();
                    }
                }
            }else if(action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)){
                if (PrinterAPI.getInstance().isConnect())return;
                runnable=new Runnable() {
                    @Override
                    public void run() {

                        USBAPI usbapi=new USBAPI(MainActivity.this);
                       String mess="";
                        if ( PrinterAPI.getInstance().connect(usbapi)==PrinterAPI.SUCCESS)
                       {
                           mess="连接成功";
                       }

                       else{
                            mess="连接失败";
                       }
                        final String finalMess = mess;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, finalMess,Toast.LENGTH_LONG).show();

                            }
                        });
                   /*     PrinterAPI.getInstance().disconnect();
                        UsbNativeAPI usbapi=new UsbNativeAPI();
                        PrinterAPI.getInstance().connect(usbapi);*/
                    }
                };
                new Thread(runnable).start();

            }

        }
    }
}

