package com.sdk.esc;

import static print.Print.getNetworkInformation;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.PrintJob;
import android.print.PrintJobInfo;
import android.print.PrintManager;
import android.print.pdf.PrintedPdfDocument;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.esc.PrinterHelper;
import com.esc.Utilitys;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import print.Print;
import print.PublicFunction;
import print.WifiTool;
import print.data.NetworkInformation;
import rx.functions.Action1;


public class Activity_Main extends Activity {
    private Context thisCon = null;
    private BluetoothAdapter mBluetoothAdapter;
    private PublicFunction PFun = null;
    private PublicAction PAct = null;

    private Button btnWIFI = null;
    private Button btnBT = null;
    private Button btnUSB = null;
    private Button btnSerial = null;

    private Spinner spnPrinterList = null;
    private TextView txtTips = null;
    private Button btnOpenCashDrawer = null;
    private Button btnSampleReceipt = null;
    private Button btn1DBarcodes = null;
    private Button btnQRCode = null;
    private Button btnPDF417 = null;
    private Button btnCut = null;
    private Button btnPageMode = null;
    private Button btnSN = null;
    private Button btnPrintseif = null;
    private Button btnboxstatus = null;
    private Button btnQuantity = null;

    private EditText edtTimes = null;

    private ArrayAdapter arrPrinterList;
    private String ConnectType = "";
    private String PrinterName = "";
    private String PortParam = "";

    private UsbManager mUsbManager = null;
    private UsbDevice device = null;
    private static final String ACTION_USB_PERMISSION = "com.PRINTSDKSample";
    private PendingIntent mPermissionIntent = null;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private static String[] wifi_PERMISSIONS = {
            "android.permission.CHANGE_WIFI_STATE",
            "android.permission.ACCESS_WIFI_STATE"
    };
    String baudrate = "";
    int REQUESTCODE_FROM_ACTIVITY = 1000;
    int REQUESTCODE_FROM_ACTIVITY_IMAGE = 9999;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private final int BITMAP_BLACKW = 0;
    private final int BITMAP_SHAKE = 1;
    private final int BITMAP_GATHER = 2;

    private final int PRINT_SUCCEED = 1;
    private final int PRINT_FAILURE = 0;

    private final int PRINT_THREE_INCH = 576;
    private final int PRINT_TWO_INCH = 384;
    private final int PRINT_FOUR_INCH = 832;
    private Socket socket1;
    private Socket socket2;
    private Socket socket3;
    private Socket socket4;
    private Socket socket5;
    private OutputStream outputStream;
    private OutputStream outputStream1;
    private OutputStream outputStream2;
    private OutputStream outputStream3;
    private OutputStream outputStream4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle(BuildConfig.VERSION_NAME);
        try {
            thisCon = this.getApplicationContext();

            btnWIFI = (Button) findViewById(R.id.btnWIFI);
            btnUSB = (Button) findViewById(R.id.btnUSB);
            btnBT = (Button) findViewById(R.id.btnBT);
            btnSerial = (Button) findViewById(R.id.btnSerial);

            //edtTimes = (EditText) findViewById(R.id.edtTimes);

            spnPrinterList = (Spinner) findViewById(R.id.spn_printer_list);
            txtTips = (TextView) findViewById(R.id.txtTips);
            btnSampleReceipt = (Button) findViewById(R.id.btnSampleReceipt);
            btnOpenCashDrawer = (Button) findViewById(R.id.btnOpenCashDrawer);
            btn1DBarcodes = (Button) findViewById(R.id.btn1DBarcodes);
            btnQRCode = (Button) findViewById(R.id.btnQRCode);
            btnPDF417 = (Button) findViewById(R.id.btnPDF417);
            btnCut = (Button) findViewById(R.id.btnCut);
            btnPageMode = (Button) findViewById(R.id.btnPageMode);
            btnSN = (Button) findViewById(R.id.btnSN);
            btnPrintseif = (Button) findViewById(R.id.btnprintself);
            btnboxstatus = (Button) findViewById(R.id.btnboxstatus);
            btnQuantity = (Button) findViewById(R.id.btn_quantity);

            mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            thisCon.registerReceiver(mUsbReceiver, filter);

            PFun = new PublicFunction(thisCon);
            PAct = new PublicAction(thisCon);
            InitSetting();
            InitCombox();
            this.spnPrinterList.setOnItemSelectedListener(new OnItemSelectedPrinter());
            //Enable Bluetooth
            EnableBluetooth();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
                    if (msg.what == PRINT_SUCCEED) {
                        Toast.makeText(thisCon, "succeed", Toast.LENGTH_LONG).show();
                        dialog.cancel();
                    } else {
                        Toast.makeText(thisCon, "failure", Toast.LENGTH_LONG).show();
                        dialog.cancel();
                    }
                }
            };
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onCreate ")).append(e.getMessage()).toString());
        }
    }

    private void InitSetting() {
        String SettingValue = "";
        SettingValue = PFun.ReadSharedPreferencesData("Codepage");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Codepage", "0,PC437(USA:Standard Europe)");

        SettingValue = PFun.ReadSharedPreferencesData("Cut");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Cut", "0");    //

        SettingValue = PFun.ReadSharedPreferencesData("Cashdrawer");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Cashdrawer", "0");

        SettingValue = PFun.ReadSharedPreferencesData("Buzzer");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Buzzer", "0");

        SettingValue = PFun.ReadSharedPreferencesData("Feeds");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Feeds", "0");
    }

    //add printer list
    private void InitCombox() {
        try {
            arrPrinterList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
            String strSDKType = thisCon.getString(R.string.sdk_type);
            if (strSDKType.equals("all"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_all, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mkt"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mkt, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mprint"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mprint, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("sycrown"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_sycrown, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mgpos"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mgpos, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("ds"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_ds, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("cst"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_cst, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("other"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_other, android.R.layout.simple_spinner_item);
            arrPrinterList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            PrinterName = arrPrinterList.getItem(0).toString();
            spnPrinterList.setAdapter(arrPrinterList);
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> InitCombox ")).append(e.getMessage()).toString());
        }
    }

    private class OnItemSelectedPrinter implements OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            PrinterName = arrPrinterList.getItem(arg2).toString();
//			CapturePrinterFunction();
//			GetPrinterProperty();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    }

    //EnableBluetooth
    @SuppressLint("MissingPermission")
    private boolean EnableBluetooth() {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled())
                return true;
            mBluetoothAdapter.enable();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!mBluetoothAdapter.isEnabled()) {
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        } else {
            Log.d("SDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }

    //call back by scan bluetooth printer
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        try {
            String strIsConnected;
            switch (resultCode) {
                case RESULT_CANCELED:
                    connectBT(data.getStringExtra("SelectedBDAddress"));
//	  				strIsConnected=data.getExtras().getString("is_connected");
//	  	        	if (strIsConnected.equals("NO")) {
//	  	        		txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));
//  	                	return;
//	  	        	}
//	  	        	else {
//	  						txtTips.setText(thisCon.getString(R.string.activity_main_connected));
//	  					return;
//	  	        	}
                case Print.ACTIVITY_CONNECT_WIFI:
                    strIsConnected = data.getExtras().getString("is_connected");
                    if (strIsConnected.equals("NO")) {
                        txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));
                        return;
                    } else {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                        return;
                    }
                case Print.ACTIVITY_PRNFILE:
//	  		    	PAct.LanguageEncode();
                    PAct.BeforePrintAction();
                    String strPRNFile = data.getExtras().getString("FilePath");
                    System.out.println(strPRNFile);
                    Print.PrintBinaryFile(strPRNFile);
                    PAct.AfterPrintAction();
                    return;
                case RESULT_OK:
                    if (requestCode == REQUESTCODE_FROM_ACTIVITY) {
                        List<String> list = data.getStringArrayListExtra("paths");
                        String mFilename = list.get(0);
                        File file = new File(mFilename);
                        return;
                    } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                        setPrintDialog(data);
                        return;
                    } else if (requestCode == REQUESTCODE_FROM_ACTIVITY_IMAGE) {
                        final List<String> list = data.getStringArrayListExtra("paths");
                        if (list == null || list.size() == 0) {
                            Toast.makeText(thisCon, "请选择图片", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        AlertDialogUtil.edTextDialog(Activity_Main.this, "提示", "次数", "1", new AlertDialogUtil.setEdTextListener() {
                            @Override
                            public void onResult(String data) {
                                final int number = Integer.valueOf(data);
                                executorService.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        for (int j = 0; j < number; j++) {
                                            for (int i = 0; i < list.size(); i++) {
                                                if (list.get(i).endsWith(".bin")) {
                                                    try {
                                                        Print.PrintBinaryFile(list.get(i));
                                                    } catch (Exception e) {
                                                    }
                                                } else {
                                                    Bitmap bmp = BitmapFactory.decodeFile(list.get(i));
                                                    try {
                                                        Print.PrintBitmap(bmp, 1, 0);
                                                        bmp.recycle();
                                                    } catch (Exception e) {
                                                    }
                                                }
                                            }
                                        }

                                    }
                                });
                            }
                        });
                    }
            }
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //连接蓝牙
    private void connectBT(final String BTmac) {
        if (TextUtils.isEmpty(BTmac))
            return;
        final ProgressDialog progressDialog = new ProgressDialog(Activity_Main.this);
        progressDialog.setMessage(getString(R.string.activity_devicelist_connect));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    final int result = Print.PortOpen(thisCon, "Bluetooth," + BTmac);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result == 0)
                                txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                            else
                                txtTips.setText(thisCon.getString(R.string.activity_main_connecterr) + result);
                        }
                    });
                    progressDialog.dismiss();
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

    private void setPrintDialog(Intent data) {
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
//        List<String> path = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
        String path = selectList.get(0).getPath();
        if (path.contains("content://")) {
            Uri uri = Uri.parse(path);
            path = FileUtils.getFilePathByUri_BELOWAPI11(uri, this);
            Log.d("Print", "image path: " + path);
        }
        final Bitmap bmp = BitmapFactory.decodeFile(path);
        if (bmp == null) {
            Toast.makeText(thisCon, "Image error", Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialogUtil alertDialogUtil = new AlertDialogUtil(Activity_Main.this);
        AlertDialog.Builder builder = alertDialogUtil.setAlertDialog();
        View view = alertDialogUtil.setViewID(R.layout.item_print);
        final RadioButton rbInch3 = view.findViewById(R.id.rb_inch3);
        final RadioButton rbInch2 = view.findViewById(R.id.rb_inch2);
        final RadioButton rbInch4 = view.findViewById(R.id.rb_inch4);
        final RadioButton rbLzoNo = view.findViewById(R.id.rb_lzo_no);
        final RadioButton rbZero = view.findViewById(R.id.rb_zero);
        final RadioButton rbShake = view.findViewById(R.id.rb_shake);
        final RadioButton rbBlackW = view.findViewById(R.id.rb_bw);
        final EditText edLight = view.findViewById(R.id.ed_light);
        builder.setNegativeButton(R.string.activity_wifi_btncancel, null);
        builder.setPositiveButton(R.string.activity_global_print, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String strLight = edLight.getText().toString();
                if (TextUtils.isEmpty(strLight) || strLight.length() > 4 || !Utility.isInteger(strLight) || Integer.valueOf(strLight) < -100 || Integer.valueOf(strLight) > 100) {
                    Toast.makeText(thisCon, R.string.activity_main_light_message, Toast.LENGTH_SHORT).show();
                    return;
                }
                printImage(bmp, Integer.valueOf(strLight), rbInch3.isChecked() ? PRINT_THREE_INCH : rbInch2.isChecked() ? PRINT_TWO_INCH : rbInch4.isChecked() ? PRINT_FOUR_INCH : 0, !rbZero.isChecked(), rbShake.isChecked() ? BITMAP_SHAKE : (rbBlackW.isChecked() ? BITMAP_BLACKW : BITMAP_GATHER), !rbLzoNo.isChecked());
            }
        });
        builder.show();
    }

    public void printImage(final Bitmap bitmap, final int light, final int size, final boolean isRotate, final int sype, final boolean isLzo) {
        dialog = new ProgressDialog(Activity_Main.this);
        dialog.setMessage("Printing.....");
        dialog.setProgress(100);
        dialog.show();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                PAct.BeforePrintAction();
                Bitmap bitmapPrint = bitmap;
                if (isRotate)
                    bitmapPrint = Utility.Tobitmap90(bitmapPrint);
                if (size != 0)
                    bitmapPrint = Utility.Tobitmap(bitmapPrint, size, Utility.getHeight(size, bitmapPrint.getWidth(), bitmapPrint.getHeight()));
                int printImage = 0;
                try {
                    if (!isLzo)
                        printImage = Print.PrintBitmap(bitmapPrint, sype, light);
                    else
                        printImage = Print.PrintBitmapLZO(bitmapPrint, sype, light);
                    if (printImage >= 0) {
                        handler.sendEmptyMessage(PRINT_SUCCEED);
                    } else {
                        handler.sendEmptyMessage(PRINT_FAILURE);
                    }
                } catch (Exception e) {
                    handler.sendEmptyMessage(PRINT_FAILURE);
                }
                bitmap.recycle();
                bitmapPrint.recycle();
                PAct.AfterPrintAction();
            }
        });
    }

    private void connectionBluetooth() {
        //获取蓝牙动态权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                    ConnectType = "Bluetooth";
                    Intent intent = new Intent(thisCon, BTActivity.class);
                    intent.putExtra("TAG", 0);
                    startActivityForResult(intent, 0);
                }
            }
        });
    }

    private void connectionWifi() {
        //获取WIFI动态权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                    setWifiDialog();
                }
            }
        });
    }

    @SuppressLint("NewApi")
    public void onClickConnect(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            if (view.getId() == R.id.btnBT) {
                connectionBluetooth();
                return;
            } else if (view.getId() == R.id.btnWIFI) {
                connectionWifi();
                return;
            } else if (view.getId() == R.id.btnUSB) {
                connectUSB();
            } else if (view.getId() == R.id.btnSerial) {
                ConantSerial(Activity_Main.this);
            }
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickConnect " + ConnectType)).append(e.getMessage()).toString());
        }
    }

    private void connectUSB() {
        ConnectType = "USB";
        //USB not need call "iniPort"
        mUsbManager = (UsbManager) thisCon.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

        boolean HavePrinter = false;
        while (deviceIterator.hasNext()) {
            device = deviceIterator.next();
            int count = device.getInterfaceCount();
            for (int i = 0; i < count; i++) {
                UsbInterface intf = device.getInterface(i);
                if (intf.getInterfaceClass() == 7) {
                    Log.d("PRINT_TAG", "vendorID--" + device.getVendorId() + "ProductId--" + device.getProductId());
//							if (device.getVendorId()==8401&&device.getProductId()==28680){
//								Log.d("PRINT_TAG","123");
                    HavePrinter = true;
                    mUsbManager.requestPermission(device, mPermissionIntent);
//							}
                }
            }
        }
        if (!HavePrinter)
            txtTips.setText(thisCon.getString(R.string.activity_main_connect_usb_printer));
    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (Print.PortOpen(thisCon, device) != 0) {
                                txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                                return;
                            } else
                                txtTips.setText(thisCon.getString(R.string.activity_main_connected));

                        } else {
                            return;
                        }
                    }
                }
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        int count = device.getInterfaceCount();
                        for (int i = 0; i < count; i++) {
                            UsbInterface intf = device.getInterface(i);
                            //Class ID 7代表打印机
                            if (intf.getInterfaceClass() == 7) {
                                Print.PortClose();
                                txtTips.setText(R.string.activity_main_tips);
                            }
                        }
                    }
                }
                if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                    if (Print.IsOpened()) {
                        Log.d("Print", "BluetoothBroadcastReceiver:Bluetooth close");
//                    Print.disConnection();
//                    sendBroadcast(new Intent(ACTION_PRINT_DISCONNECTED));
                        try {
                            Print.PortClose();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        txtTips.setText(R.string.activity_main_tips);
                        Utility.show(thisCon, getString(R.string.activity_main_close));
                    }
                } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            Log.d("Print", "STATE_OFF 手机蓝牙关闭");
                            if (Print.IsOpened()) {
                                Log.d("Print", "BluetoothBroadcastReceiver:Bluetooth close");
                                try {
                                    Print.PortClose();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                txtTips.setText(R.string.activity_main_tips);
                                Utility.show(thisCon, getString(R.string.activity_main_close));
                            }
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.d("Print", "STATE_TURNING_OFF 手机蓝牙正在关闭");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.d("Print", "STATE_ON 手机蓝牙开启");
                            break;
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.d("Print", "STATE_TURNING_ON 手机蓝牙正在开启");
                            break;
                    }
                }
            } catch (Exception e) {
                Log.e("SDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
            }
        }
    };
    private Handler handler;
    private ProgressDialog dialog;

    public void onClickClose(View view) {
        if (!checkClick.isClickEvent()) return;

        try {

            Print.PortClose();

            this.txtTips.setText(R.string.activity_main_tips);
            return;
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }

    public void onClickbtnSetting(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            startActivity(new Intent(Activity_Main.this, Activity_Setting.class));
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }

    public void onClickDo(View view) throws Exception {
        if (!checkClick.isClickEvent()) return;
        if (!Print.IsOpened()) {
            Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();
            return;
        }
        if (view.getId() == R.id.btnGetStatus) {
            getPrintStatus();
        } else if (view.getId() == R.id.btnOpenCashDrawer) {
            Intent myIntent = new Intent(this, Activity_Cashdrawer.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnSampleReceipt) {
            PrintSampleReceipt();
        } else if (view.getId() == R.id.btn1DBarcodes) {
            Intent myIntent = new Intent(this, Activity_1DBarcodes.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnCut) {
            Intent myIntent = new Intent(this, Activity_Cut.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnTextFormat) {
            Intent myIntent = new Intent(this, Activity_TextFormat.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnPrintImageFile) {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean)
                        setImageDialog();
                }
            });
        } else if (view.getId() == R.id.btnPrintCardRead) {
            Activity_Magnetic_Card.startActivity(this);
        } else if (view.getId() == R.id.btnPageMode) {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean)
                        printPDF();
                }
            });
        } else if (view.getId() == R.id.btnQRCode) {
            Intent myIntent = new Intent(this, Activity_QRCode.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnPDF417) {
            Intent myIntent = new Intent(this, Activity_PDF417.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnSN) {
            getPrinterSN();
        } else if (view.getId() == R.id.btnPrintTestPage) {
            PrintTestPage();
//            printTest();
//            test();
        } else if (view.getId() == R.id.btnprintself) {
            printSelf();
        } else if (view.getId() == R.id.btnboxstatus) {
            getCashDrawer();
        } else if (view.getId() == R.id.btnsiyuan) {
            printSiYuan();
        } else if (view.getId() == R.id.btn_quantity) {
            getPrinterQuantity();
        } else if (view.getId() == R.id.btn_density) {
            setDensity();
        } else if (view.getId() == R.id.btn_network) {
            getNetworkInformation();
        } else if (view.getId() == R.id.btn_set_network) {
            setNetworkParameter();
        }
    }

    private void setNetworkParameter() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        View inflate = LayoutInflater.from(Activity_Main.this).inflate(R.layout.item_network, null);
        builder.setView(inflate);
        RadioButton rbDhcpYes = inflate.findViewById(R.id.rb_dhcp_yes);
        EditText edIP = inflate.findViewById(R.id.ed_ip);
        EditText edSubnetMask = inflate.findViewById(R.id.ed_subnet_mask);
        EditText edGateway = inflate.findViewById(R.id.ed_gateway);
        builder.setPositiveButton(R.string.main_setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Print.setDHCP(rbDhcpYes.isChecked() ? 1 : 0);
                Print.setPrintIP(edIP.getText().toString());
                Print.setPrintSubnetMask(edSubnetMask.getText().toString());
                Print.setPrintGateway(edGateway.getText().toString());
                switch (Print.setPrintSave()) {
                    case Print.SUCCEED:
                        Utility.show(Activity_Main.this, getString(R.string.setting_success));
                        break;
                    case Print.ERROR_SAVE_FAIL:
                        Utility.show(Activity_Main.this, getString(R.string.setting_fail));
                        break;
                    case Print.ERROR_NO_CONNECT:
                        Utility.show(Activity_Main.this, getString(R.string.send_fail));
                        break;
                }
            }
        });
        builder.setNegativeButton(R.string.activity_wifi_btncancel, null);
        builder.show();
    }

    private void getNetworkInformation() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                int dhcp = Print.isDHCP();
                String printIP = Print.getPrintIP();
                String printSubnetMask = Print.getPrintSubnetMask();
                String printGateway = Print.getPrintGateway();
                NetworkInformation networkInformation = new NetworkInformation();
                networkInformation.setDhcp(dhcp == 1);
                networkInformation.setIp(printIP);
                networkInformation.setSubnetMask(printSubnetMask);
                networkInformation.setGateway(printGateway);
                if (networkInformation == null) {
                    Utility.show(Activity_Main.this, getString(R.string.activity_devicelist_get_device_err));
                } else {
                    Utility.show(Activity_Main.this, networkInformation.toString());
                }
            }
        });
    }

    private void setDensity() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        String[] str = new String[]{"1", "2", "3", "4"};
        builder.setTitle(getString(R.string.activity_main_density));
        builder.setItems(str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    PrinterHelper.WriteData(new byte[]{0x12, 0x01, (byte) (which + 1)});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        builder.show();
    }

    private void getPrinterQuantity() {
        int printerQuantity = Print.getPrinterQuantity();
        if (printerQuantity == -1) {
            Toast.makeText(thisCon, getString(R.string.activity_devicelist_get_device_err), Toast.LENGTH_SHORT).show();
            return;
        }
        if (printerQuantity == -2) {
            Toast.makeText(thisCon, getString(R.string.acticity_main_nonsupport), Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(thisCon, "" + printerQuantity, Toast.LENGTH_SHORT).show();
    }

    private void printSiYuan() {
        try {
            Print.printSiYuanText(32, "测试思源32字体");
            Print.printSiYuanText(36, "测试思源36字体");
            Print.printSiYuanText(42, "测试思源42字体");
        } catch (Exception e) {
        }
    }

    private void getCashDrawer() {
        Log.d("Print", "getCashDrawer: start");
        try {
            while (Print.ReadData(200).length > 0) {
            }
            Print.WriteData(new byte[]{0x1D, 0x72, 0x02});
            byte[] status = Print.ReadData(2000);
            if (status == null || status.length != 1) {
                Utility.show(thisCon, "time out");
                return;
            }
            Log.d("Print", "getCashDrawer: status " + status[0]);
            if (status[0] == 1) {
                Utility.show(this, "Cash Drawer Close");
            } else if (status[0] == 0) {
                Utility.show(this, "Cash Drawer Open");
            } else {
                Utility.show(this, "Data Error");
            }
        } catch (Exception e) {
        }
    }

    private void getPrintStatus() {
        try {
            String statusStr = "";
            byte[] bytes = Print.GetRealTimeStatus((byte) 2);
            if ((bytes[0] & 4) == 4) {
                //开盖
                statusStr = getString(R.string.activity_status_real_time_status_cover_is_open);
            } else {
                //合盖
                statusStr = getString(R.string.activity_status_real_time_status_cover_is_close);
            }
            byte[] bytes1 = Print.GetRealTimeStatus((byte) 4);
            if ((bytes1[0] & 96) == 96) {
                //无纸
                statusStr = statusStr + " " + getString(R.string.activity_status_transmit_status_no_paper);
            } else {
                //有纸
                statusStr = statusStr + " " + getString(R.string.activity_status_transmit_status_has_paper);
            }
            if ((bytes1[0] & 12) == 12) {
                //纸将尽
                statusStr = statusStr + " " + getString(R.string.activity_status_real_time_status_paper_near_end);
            } else {
                //纸充足
                statusStr = statusStr + " " + getString(R.string.activity_status_real_time_status_paper_adquate);
            }
            if (TextUtils.isEmpty(statusStr))
                return;
            Toast.makeText(thisCon, statusStr, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        }
    }

    private void printSelf() {
        try {
            Print.printSelf();
        } catch (Exception e) {
        }
    }

    private void getPrinterSN() {
        try {
            String printSN = Print.getPrintSN();
            if (TextUtils.isEmpty(printSN)) {
                Toast.makeText(thisCon, thisCon.getText(R.string.activity_devicelist_get_device_err), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(thisCon, printSN, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
        }
    }


    private void printTest() {
        try {
//            Print.WriteData(new byte[]{0x1B, 0x1C, 0x26, 0x20, 0x56, 0x31, 0x20, 0x67, 0x65,
//                    0x74, 0x76, 0x61, 0x6C, 0x20, 0x22, 0x63, 0x6F, 0x6E, 0x73, 0x75, 0x6D, 0x65,
//                    0x5F, 0x70, 0x6F, 0x77, 0x65, 0x72, 0x22, 0x0D, 0x0A});
            Print.WriteData(new byte[]{0x1B, 0x1C, 0x26, 0x20, 0x56, 0x31, 0x20, 0x67, 0x65, 0x74,
                    0x76, 0x61, 0x6C, 0x20, 0x22, 0x63, 0x6F, 0x6E, 0x73, 0x75, 0x6D, 0x65, 0x5F,
                    0x63, 0x75, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x22, 0x0D, 0x0A});
            byte[] bytes = Print.ReadData(1000);
            Log.d("Print", "printTest: " + PrinterHelper.bytetohex(bytes));
//            Print.WriteData(new byte[]{0x1d, 0x28, 0x41, 0x02, 0x00, 0x00, 02});
        } catch (Exception e) {
        }
    }


    private void printPDF() {
        new LFilePicker()
                .withActivity(this)
                .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                .withStartPath(Environment.getExternalStorageDirectory().getAbsolutePath())
                .withTitle(getResources().getString(R.string.activity_esc_function_btnpagemode))
                .withMutilyMode(false)
                .withBackgroundColor("#000000")
                .withTitleColor("#ffffff")
                .withFileFilter(new String[]{".PDF", ".pdf"})
                .start();
    }

    private void setImageDialog() {

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
                .isWeChatStyle(true)// 是否开启微信图片选择风格
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    public class GlideLoader implements com.yancy.imageselector.ImageLoader {

        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context)
                    .load(path)
//                    .placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
                    .centerCrop()
                    .into(imageView);
        }
    }

    public void PrintTestPage() {
        try {
            PAct.BeforePrintAction();
            String strPrintText = "Print SDK Sample!";
            Print.PrintText(thisCon.getString(R.string.activity_main_originalsize) + strPrintText + "\n", 0, 0, 0);
            Print.PrintText(thisCon.getString(R.string.activity_main_bold) + strPrintText + "\n", 0, 2, 0);
            Print.PrintText(thisCon.getString(R.string.activity_main_underline) + strPrintText + "\n", 0, 4, 0);
            Print.PrintText(thisCon.getString(R.string.activity_main_minifront) + strPrintText + "\n", 0, 1, 0);
            Barcode_BC_UPCA();
            Barcode_BC_UPCE();
            Barcode_BC_EAN8();
            Barcode_BC_EAN13();
            Barcode_BC_CODEBAR();
            Barcode_BC_ITF();
            Barcode_BC_CODE128();
            PAct.AfterPrintAction();
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
        }
    }

    private int Barcode_BC_UPCA() throws Exception {
        Print.PrintText("BC_UPCA:\n");
        return Print.PrintBarCode(Print.BC_UPCA,
                "075678164125");
    }

    private int Barcode_BC_UPCE() throws Exception {
        Print.PrintText("BC_UPCE:\n");
        return Print.PrintBarCode(Print.BC_UPCE,
                "01227000009");//04252614
    }

    private int Barcode_BC_EAN8() throws Exception {
        Print.PrintText("BC_EAN8:\n");
        return Print.PrintBarCode(Print.BC_EAN8,
                "04210009");
    }

    private int Barcode_BC_EAN13() throws Exception {
        Print.PrintText("BC_EAN13:\n");
        return Print.PrintBarCode(Print.BC_EAN13,
                "6901028075831");
    }

    private int Barcode_BC_CODE93() throws Exception {
        Print.PrintText("BC_CODE93:\n");
        return Print.PrintBarCode(Print.BC_CODE93,
                "TEST93");
    }

    private int Barcode_BC_CODE39() throws Exception {
        Print.PrintText("BC_CODE39:\n");
        return Print.PrintBarCode(Print.BC_CODE39,
                "123456789");
    }

    private int Barcode_BC_CODEBAR() throws Exception {
        Print.PrintText("BC_CODEBAR:\n");
        return Print.PrintBarCode(Print.BC_CODEBAR,
                "A40156B");
    }

    private int Barcode_BC_ITF() throws Exception {
        Print.PrintText("BC_ITF:\n");
        return Print.PrintBarCode(Print.BC_ITF,
                "123456789012");
    }

    private int Barcode_BC_CODE128() throws Exception {
        Print.PrintText("BC_CODE128:\n");
        return Print.PrintBarCode(Print.BC_CODE128,
                "{BS/N:{C\014\042\070\116{A3");    // decimal 1234 = octonary 1442
    }


    private void PrintSampleReceipt() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Print.Initialize();
                    PAct.BeforePrintAction();
                    String[] ReceiptLines = getResources().getStringArray(R.array.activity_main_sample_2inch_receipt);
                    String str = "";
                    for (int i = 0; i < ReceiptLines.length; i++) {
                        str += ReceiptLines[i];
                    }
                    int result = Print.PrintText(str);
                    PAct.AfterPrintAction();
                    Thread.sleep(500);
                    Print.PortClose();
                } catch (Exception e) {
                    Log.e("Print", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
                }
            }
        });
    }

    private void ConantSerial(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_serial_dialog, null);
        final Spinner sp_serial_baudrate = (Spinner) inflate.findViewById(R.id.sp_serial_baudrate);
        final String[] sList = new String[]{"9600", "14400", "19200", "115200"};
        arrPrinterList = new ArrayAdapter<String>(Activity_Main.this, android.R.layout.simple_spinner_item, sList);
        sp_serial_baudrate.setAdapter(arrPrinterList);
        sp_serial_baudrate.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                baudrate = sList[position];
            }

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

            }
        });
        final EditText ed_serial_port = (EditText) inflate.findViewById(R.id.ed_serial_port);
        builder.setPositiveButton(getResources().getString(R.string.activity_wifi_btnconnect), new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String port = ed_serial_port.getText().toString();
                if ("".equals(baudrate)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_nobaudrate), Toast.LENGTH_LONG).show();
                    return;
                }
                if ("".equals(port)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_noport), Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    int portOpen = Print.PortOpen(thisCon, "Serial," + port + "," + baudrate);
                    if (portOpen == -1) {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                    } else {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                    }
                } catch (Exception e) {
                    txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                }
            }
        });
        builder.setNegativeButton(getString(R.string.activity_wifi_btncancel), null);
        builder.setView(inflate);
        builder.show();
    }

    private void setWifiDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        String[] str = new String[]{getString(R.string.wifi_select_ip_connection), getString(R.string.wifi_select_udp_connection)};
        builder.setItems(str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        ConnectType = "WiFi";
                        Intent serverIntent = new Intent(thisCon, Activity_Wifi.class);
                        serverIntent.putExtra("PN", PrinterName);
                        startActivityForResult(serverIntent, Print.ACTIVITY_CONNECT_WIFI);
                        break;
                    case 1:
                        connectionUDP();
                        break;
                    default:
                        break;
                }
            }
        });
        builder.show();
    }

    private void connectionUDP() {
        if (!WifiTool.isWifi(thisCon)) {
            Toast.makeText(thisCon, "please connection wifi", Toast.LENGTH_SHORT).show();
            return;
        }
        startActivityForResult(new Intent(Activity_Main.this, Activity_UDP.class), 100);
    }

    private void printTable() {
        try {
            Print.Initialize();//初始化
            Print.setPrintResolution(203, 203);
            Print.SelectPageMode();//页模式
            Print.SetPageModePrintArea(0, 0, 640, 1440);//区域(起始x，起始y，宽，高)
            Print.SetPageModePrintDirection(3);//方向（0：0度，1：90度，2：180度，3：270度）
            Print.SetPageModeAbsolutePosition(362, 48);//横坐标 纵坐标
            Print.SetCharacterSize(17);//字体
            Print.PrintText("北京锦纶国际物流托运单");
            Print.SetPageModeAbsolutePosition(01, 72);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("货号：济南171117-北京001-1                 2017年11月17日");

            Print.SetPageModeAbsolutePosition(1088, 72);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("票号：100503446");
            Print.PrintPageRectangle(0, 80, 1280, 480, 2);//矩形框（起始x，起始Y，终点x，终点Y，线条宽度）
            Print.SetPageModeAbsolutePosition(16, 120);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("收 货 人      245        电 话         2452245           货 名          2         重 量           0");
            Print.PrintPageLine(0, 128, 1280, 128, 2);//线条（起始x，起始Y，终点x，终点Y，线条宽度）
            Print.SetPageModeAbsolutePosition(16, 168);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("收 货 人      2452       电 话         2452245           件 数          2         体 积           0");
            Print.PrintPageLine(0, 176, 1280, 176, 2);
            Print.SetPageModeAbsolutePosition(16, 216);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText(" 提 付    现 付  回单付   货款扣   返 款   代收货款    手续费       运货费       保价         中转费");
            Print.PrintPageLine(0, 224, 1280, 224, 2);
            Print.SetPageModeAbsolutePosition(16, 264);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("   2        0      0       0        0        5           回：1          0           0           0");
            Print.PrintPageLine(0, 272, 1280, 272, 2);
            Print.SetPageModeAbsolutePosition(16, 312);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText(" 会员号                   帐 号                                    到站合计               7");
            Print.PrintPageLine(0, 320, 1280, 320, 2);
            Print.SetPageModeAbsolutePosition(8, 360);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("委托单号                 回单要求                                   交货方式              自提");
            Print.PrintPageLine(0, 368, 1280, 368, 2);
            Print.SetPageModeAbsolutePosition(8, 408);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("委托地址   城环城： 五方： 西部： 神龙丰  56209689/87561903          客户签名");
            Print.PrintPageLine(0, 416, 1280, 416, 2);
            Print.SetPageModeAbsolutePosition(8, 456);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("到货地址   济南市老屯汽配城北门3#  0531-82533880");
            Print.PrintPageLine(0, 464, 1280, 464, 2);
            Print.SetPageModeAbsolutePosition(4, 496);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("托运人须知：");
            Print.SetPageModeAbsolutePosition(904, 504);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("备 注");
            Print.PrintPageLine(880, 520, 1280, 520, 2);
            Print.SetPageModeAbsolutePosition(904, 544);
            Print.SetCharacterSize((byte) 0);
            Print.PrintText("操作员：北京10：40：37");
            Print.PrintPageLine(128, 80, 128, 464, 2);
            Print.PrintPageLine(208, 176, 208, 272, 2);
            Print.PrintPageLine(288, 80, 288, 368, 2);
            Print.PrintPageLine(416, 80, 416, 368, 2);
            Print.PrintPageLine(496, 176, 496, 272, 2);
            Print.PrintPageLine(656, 80, 656, 272, 2);
            Print.PrintPageLine(800, 80, 800, 416, 2);
            Print.PrintPageLine(968, 80, 968, 416, 2);
            Print.PrintPageLine(1120, 80, 1120, 272, 2);
            Print.PrintPageLine(880, 464, 880, 560, 2);
            Print.PrintPageLine(968, 464, 968, 520, 2);
            Print.SetPageModePrintDirection(0);
            Print.SetPageModeAbsolutePosition(288, 1350);
            Print.PrintBarCode(72, "123456789", 3, 50, 0, 2);
            Print.PrintDataInPageMode();//打印

        } catch (Exception e) {
            Log.e("Print", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Print.PortClose();
        } catch (Exception e) {
        }
    }

    public void test() {
        try {
            InputStream input = getResources().getAssets().open("ic.jpg");
            SimpleImageInfo simpleImageInfo = new SimpleImageInfo(input);
            Log.d("Print", "simpleImageInfo: " + simpleImageInfo.toString());
        } catch (Exception e) {
        }
    }

    public void test(View view) {
        printTest();
    }
}
