package android_serialport_api.print_tool; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Toast; import com.ectrip.cyt.config.MyApp; import com.ectrip.cyt.constant.DeviceType; import com.ectrip.cyt.constant.LogoType; import com.ectrip.cyt.constant.SelectAction; import com.ectrip.cyt.constant.constant; import com.ectrip.cyt.shield_home.LockLayer.MToast; import com.ectrip.cyt.ui.DeviceListActivity; import com.ectrip.cyt.utils.LogUtil; import com.ectrip.cyt.utils.SharedPreferences2Obj; import com.ectrip.trips.check.R; import com.eztlib.BluetoothService; import com.eztlib.PrinterEscCmd; import com.eztlib.blu.PairUtil; /** * @author jigo 手机、手持机打印 */ public class MobilePrintTool extends Activity { private String TAG = "MobilePrintTool"; private String info; private PrinterEscCmd printer;// 蓝牙打印的类 private Integer type = null;// 设备类型 public BluetoothService mService = null; // 请求的代码 public final int REQUEST_CONNECT_DEVICE = 15; private final int REQUEST_ENABLE_BT = 16; public final int PRINT_RESPONSE = 10; private BluetoothAdapter mBluetoothAdapter = null;// 当地蓝牙适配器 private boolean isOpen = false; private boolean isturn = false; private boolean isprint = false; private boolean isprint2 = false; private String isStatistic = "0"; private MyHandler myHandler = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mobel_tool); initView(); try { isStatistic = SharedPreferences2Obj .getInstance(MobilePrintTool.this).setName("SelectAction") .getObject("isStatistic", String.class); // 非统计判断 init(getIntent().getStringExtra("info")); } catch (Exception e) { e.printStackTrace(); finish(); } myHandler = new MyHandler(); } @Override protected void onResume() { super.onResume(); if (isprint) { finish(); } } public void initView() { findViewById(R.id.retryButton).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { adapterCallback(); } }); findViewById(R.id.topBack).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void init(String info) { this.info = info; if (printer == null) { printer = new PrinterEscCmd(); } type = SharedPreferences2Obj.getInstance(MobilePrintTool.this) .setName("MachineType").getObject("type", Integer.class); if (initBlu()) { initBS(); } } private boolean initBlu() { // 判断是否有蓝牙功能 // 得到本地的适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { if (type != null && type == DeviceType.HANDSET.getValue()) { MToast.makeText(MobilePrintTool.this, getString(R.string.bluetooth_not_available), MToast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(MobilePrintTool.this, R.string.bluetooth_not_available, Toast.LENGTH_LONG) .show(); finish(); } return false; } return true; } private void initBS() { // 初始化mService if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { isOpen = false; if (turnOnBluetooth()) { openBluDevices(); } else { Intent enableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } if (type != null && type == DeviceType.HANDSET.getValue()) { // 手持机强制打开 adapterCallback(); } } else { isOpen = true; if (mService == null) { mService = new BluetoothService(MobilePrintTool.this, mHandler); } adapterCallback(); } } public void adapterCallback() { // 跳转到驱动页面 if (initBlu()) { if (mBluetoothAdapter.isEnabled()) { if (mService != null) { if (mService.getState() == BluetoothService.STATE_NONE) { mService.start(); } } else { mService = new BluetoothService(MobilePrintTool.this, mHandler); } openBluDevices(); } else { if (type != null && type == DeviceType.HANDSET.getValue()) { // 先试着强制打开时,不行者弹框打开 if (turnOnBluetooth()) { openBluDevices(); } else { Intent enableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } } else { Intent enableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } } } } /** * 强制开启当前 Android 设备的 Bluetooth * * @return true:强制打开 Bluetooth 成功 false:强制打开 Bluetooth 失败 */ public boolean turnOnBluetooth() { if (mBluetoothAdapter != null) { return mBluetoothAdapter.enable(); } return false; } private void openBluDevices() { // 打开连接蓝牙设备页面 if (!isturn && mBluetoothAdapter.isEnabled()) { Intent intent = new Intent(MobilePrintTool.this, DeviceListActivity.class); startActivityForResult(intent, REQUEST_CONNECT_DEVICE); isturn = true; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CONNECT_DEVICE: // 当DeviceListActivity返回一个设备连接 if (resultCode == Activity.RESULT_OK) { // 获取设备的MAC地址 String address = data.getExtras().getString( DeviceListActivity.EXTRA_DEVICE_ADDRESS); // 得到BLuetoothDevice对象 if (address == null) { break; } LogUtil.i("address" + address); // 获取设备进行连接 BluetoothDevice device = mBluetoothAdapter .getRemoteDevice(address); try { if (type != null && type == DeviceType.HANDSET.getValue() && device.getBondState() != BluetoothDevice.BOND_BONDED) { PairUtil.pair(address, constant.pair, device); } } catch (Exception e1) { e1.printStackTrace(); } // 尝试连接到设备 if (device != null) { try { mService.connect(device); } catch (Exception e) { e.printStackTrace(); } } else { finish(); } } else { finish(); } break; case REQUEST_ENABLE_BT: // 当请求激活蓝牙的回报 if (!isOpen) { adapterCallback(); } if (resultCode == Activity.RESULT_OK) { // 蓝牙现在是启用的,因此,建立一个聊天会话 // 蓝牙开启成功,则继续初始化UI if (mService == null) { mService = new BluetoothService(MobilePrintTool.this, mHandler); } // openBluDevices(); } else { // 用户没有启用蓝牙或出错 LogUtil.d(TAG, "BT not enabled"); } default: break; } } private void print(final String str) { if (isprint && isprint2) { isprint2 = false; if (printer == null) { printer = new PrinterEscCmd(); } final int printNum = MyApp.getInstance().getPrintNum(); LogUtil.d(printNum + getString(R.string.times)); new Thread(new Runnable() { @Override public void run() { printThread(printNum, str); } }).start(); } } @SuppressLint("SimpleDateFormat") private void printThread(int printNum, List str) { for (int x = 0; x < printNum; x++) { if (x == 1 && isStatistic.equals("1")) { if (dialog != null) { dialog.dismiss(); } return; } try { if (isStatistic != null && isStatistic.equals("1")) { printer.escPrintText(" 统计信息" + "\n"); } else { printer.escPrintText(" 订单信息"); // 当时重打小票的时候,多打一段字符 int Select = SharedPreferences2Obj .getInstance(MobilePrintTool.this) .setName("SelectAction") .getObject("Select", Integer.class); if (Select == SelectAction.Reprint.getValue()) { printer.escEnter(); printer.escPrintText(" (重打小票)"); } } printer.escEnter(); } catch (Exception e) { e.printStackTrace(); } if (str == null) { return; } // 打印信息 try { if (isStatistic != null && isStatistic.equals("1")) { System.out.println(str); try { for (int i = 0; i < str.size(); i++) { printer.escPrintText(str.get(i));// 订单信息 } } catch (Exception e) { e.printStackTrace(); } } else { int Select = SharedPreferences2Obj .getInstance(MobilePrintTool.this) .setName("SelectAction") .getObject("Select", Integer.class); if (Select == SelectAction.Query.getValue()) { // 打印时间 SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 设置日期格式 printer.escPrintText("检票时间:" + df.format(new Date()));// new printer.escEnter(); // Date()为获取当前系统时间 }else if (Select == SelectAction.Reprint.getValue()) {// 重打时间 SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 设置日期格式 //printer.escPrintText("重打时间:" + df.format(new Date()));// new printer.escEnter(); // Date()为获取当前系统时间 } for (int i = 0; i < str.size(); i++) { printer.escPrintText(str.get(i));// 订单信息 } printer.escEnter(); printer.escPrintText("取票人签名:" + "\n"); } if (constant.logoMark == LogoType.CYT.getValue()) { printer.escEnter(); printer.escPrintText("---畅游通—智慧旅游O2O平台---"); printer.escEnter(); printer.escPrintText("--------www.jingqu.cn---------"); } else if (constant.logoMark == LogoType.QNE.getValue()) { printer.escEnter(); printer.escPrintText("---欢迎使用去哪儿网O2O系统---"); printer.escEnter(); printer.escPrintText("--------www.qunar.com--------"); } printer.escEnter(); sleep(2000); } catch (Exception e) { e.printStackTrace(); } // 信息完打印的空格行数 try { printer.escEnter(); printer.escEnter(); printer.escEnter(); if ((x + 1) == printNum) { myHandler.sendMessage(myHandler .obtainMessage(FINISH_ACTIVITY)); } } catch (Exception e) { e.printStackTrace(); } } } @SuppressLint("SimpleDateFormat") private void printThread(int printNum, String str) { for (int x = 0; x < printNum; x++) { if (x == 1 && isStatistic.equals("1")) { if (dialog != null) { dialog.dismiss(); } return; } try { if (isStatistic != null && isStatistic.equals("1")) { printer.escPrintText(" 统计信息" + "\n"); } else { printer.escPrintText(" 订单信息"); // 当时重打小票的时候,多打一段字符 int Select = SharedPreferences2Obj .getInstance(MobilePrintTool.this) .setName("SelectAction") .getObject("Select", Integer.class); if (Select == 2) { printer.escEnter(); printer.escPrintText(" (重打小票)"); } } printer.escEnter(); } catch (Exception e) { e.printStackTrace(); } if (str == null) { return; } // 打印信息 try { if (isStatistic != null && isStatistic.equals("1")) { System.out.println(str); try { printer.escPrintText(str);// 订单信息 } catch (Exception e) { e.printStackTrace(); } } else { // 重打时间 int Select = SharedPreferences2Obj .getInstance(MobilePrintTool.this) .setName("SelectAction") .getObject("Select", Integer.class); if (Select == 2) { SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 设置日期格式 printer.escPrintText("重打时间:" + df.format(new Date()));// new printer.escEnter(); // Date()为获取当前系统时间 } printer.escPrintText(str);// 订单信息 printer.escEnter(); printer.escPrintText("取票人签名:" + "\n"); } if (constant.logoMark == LogoType.CYT.getValue()) { printer.escEnter(); printer.escPrintText("---畅游通—智慧旅游O2O平台---"); printer.escEnter(); printer.escPrintText("--------www.jingqu.cn---------"); } else if (constant.logoMark == LogoType.QNE.getValue()) { printer.escEnter(); printer.escPrintText("---欢迎使用去哪儿网O2O系统---"); printer.escEnter(); printer.escPrintText("--------www.qunar.com--------"); } try { printer.escEnter(); printer.escEnter(); printer.escEnter(); printer.escEnter(); } catch (Exception e) { e.printStackTrace(); } sleep(2000); } catch (Exception e) { e.printStackTrace(); } finally { if ((x + 1) == printNum) { myHandler.sendMessage(myHandler .obtainMessage(FINISH_ACTIVITY)); } } } } private final int FINISH_ACTIVITY = 10; @SuppressLint("HandlerLeak") class MyHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case FINISH_ACTIVITY: sleep(2000); if (mService != null) { mService.stop(); } if (mBluetoothAdapter != null) { mBluetoothAdapter.cancelDiscovery(); if (mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.disable(); } } Intent intent = new Intent(); setResult(2, intent); finish(); break; default: break; } } } public void sleep(int ms) { try { java.lang.Thread.sleep(ms); } catch (Exception e) { e.printStackTrace(); } } // 蓝牙连接等待弹框 private ProgressDialog dialog = null; // 连接的设备的名称 private String mConnectedDeviceName = null; // 更新标题栏右边状态和读写状态的Handler @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case BluetoothService.MESSAGE_STATE_CHANGE: switch (msg.arg1) { case BluetoothService.STATE_CONNECTED: MyApp.getInstance().setBluConnection(true); if (!isprint) { isprint = true; isprint2 = true; } print(info); if (dialog != null) { dialog.dismiss(); dialog = null; } break; case BluetoothService.STATE_CONNECTING: if (dialog == null) { // 显示ProgressDialog dialog = new ProgressDialog(MobilePrintTool.this); dialog.setMessage("连接打印机中..."); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); if (type == DeviceType.HANDSET.getValue()) { dialog.getWindow() .setType( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); } try { dialog.show(); } catch (Exception e) { e.printStackTrace(); } } else { dialog.setMessage("连接打印机中..."); } break; case BluetoothService.STATE_NONE: break; case BluetoothService.STATE_LISTEN: // MyApp.getInstance().setBluConnection(false); if (dialog != null) { dialog.dismiss(); dialog = null; } break; case BluetoothService.STATE_FAILL: if (dialog != null) { dialog.dismiss(); dialog = null; } finish(); break; } break; case BluetoothService.STATE_FAILL: if (dialog != null) { dialog.dismiss(); dialog = null; } finish(); break; case BluetoothService.MESSAGE_WRITE: break; case BluetoothService.MESSAGE_READ: break; case BluetoothService.MESSAGE_DEVICE_NAME: // 保存连接设备的名字 mConnectedDeviceName = msg.getData().getString( BluetoothService.DEVICE_NAME); if (type != null && type == DeviceType.HANDSET.getValue()) { MToast.makeText(MobilePrintTool.this, "连接到" + mConnectedDeviceName, MToast.LENGTH_SHORT) .show(); } else { Toast.makeText(MobilePrintTool.this, "连接到" + mConnectedDeviceName, Toast.LENGTH_SHORT) .show(); } if (!isprint) { isprint = true; isprint2 = true; } print(info); break; case BluetoothService.MESSAGE_TOAST: if (!msg.getData().getBoolean("sucess", false)) { finish(); return; } if (Thread.currentThread() != Looper.getMainLooper() .getThread()) { Looper.prepare(); } String info = msg.getData().getString(BluetoothService.TOAST); if (info != null && !info.equals("")) { if (type != null && type == DeviceType.HANDSET.getValue()) { MToast.makeText( MobilePrintTool.this, msg.getData().getString(BluetoothService.TOAST), MToast.LENGTH_LONG).show(); } else { Toast.makeText( MobilePrintTool.this, msg.getData().getString(BluetoothService.TOAST), Toast.LENGTH_LONG).show(); } if (Thread.currentThread() != Looper.getMainLooper() .getThread()) { Looper.loop(); } } break; } } }; @Override protected void onDestroy() { super.onDestroy(); if (mBluetoothAdapter != null) { mBluetoothAdapter.cancelDiscovery(); if (mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.disable(); } } } }