BlueToothPrintAct.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package com.uas.hystorage.activity;
  2. import android.bluetooth.BluetoothDevice;
  3. import android.content.Intent;
  4. import android.graphics.drawable.BitmapDrawable;
  5. import android.os.Build;
  6. import android.os.Bundle;
  7. import android.support.v7.widget.LinearLayoutManager;
  8. import android.support.v7.widget.RecyclerView;
  9. import android.text.TextUtils;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.view.animation.Animation;
  13. import android.view.animation.LinearInterpolator;
  14. import android.view.animation.RotateAnimation;
  15. import android.widget.Button;
  16. import android.widget.ImageView;
  17. import android.widget.LinearLayout;
  18. import android.widget.PopupWindow;
  19. import android.widget.TextView;
  20. import com.alibaba.fastjson.JSON;
  21. import com.alibaba.fastjson.JSONArray;
  22. import com.alibaba.fastjson.JSONObject;
  23. import com.chad.library.adapter.base.BaseQuickAdapter;
  24. import com.chad.library.adapter.base.BaseViewHolder;
  25. import com.uas.bluetooth.ConnectHelper;
  26. import com.uas.hystorage.R;
  27. import com.uas.hystorage.adapter.BluetoothAdapter;
  28. import com.uas.hystorage.tools.SharedPreUtil;
  29. import com.uas.hystorage.util.CommonUtil;
  30. import com.uas.hystorage.util.Constants;
  31. import com.uas.hystorage.util.FastjsonUtil;
  32. import com.uas.hystorage.util.ListUtils;
  33. import com.uas.hystorage.util.PrintUtils;
  34. import com.uas.hystorage.view.RecyclerItemDecoration;
  35. import com.yanzhenjie.permission.Action;
  36. import com.yanzhenjie.permission.AndPermission;
  37. import com.yanzhenjie.permission.Permission;
  38. import java.util.ArrayList;
  39. import java.util.List;
  40. import java.util.Set;
  41. import vn.luongvo.widget.iosswitchview.SwitchView;
  42. public class BlueToothPrintAct extends BaseActivity {
  43. public static final int REQUEST_ENABLE_BT = 1;//开启蓝牙的请求回调
  44. private ImageView mRefreshImageView;
  45. private SwitchView mSwitchView;
  46. private TextView mDpiTextView;
  47. private RecyclerView mRecyclerView;
  48. private ConnectHelper connectHelper;
  49. private RotateAnimation mRotateAnimation;//动画
  50. private BluetoothAdapter mBluetoothAdapter;
  51. private boolean isConnected = false;
  52. private String mOldAddress = "";
  53. private List<Integer> mDpiList;
  54. private View mMenuView;
  55. private PopupWindow mMenuPopupWindow;
  56. private RecyclerView mMenuRecyclerView;
  57. private BaseQuickAdapter<Integer, BaseViewHolder> mMenuAdapter;
  58. private int mDpi;
  59. private String mPrintJson;
  60. private int mRetryCount = 0;
  61. private boolean isPrinting = false;
  62. private Button bt_return;
  63. private TextView tv_title;
  64. private ImageView iv_icon;
  65. private TextView tv_type;
  66. @Override
  67. protected void initViews() {
  68. setContentView(R.layout.act_blue_tooth_print);
  69. bt_return = findViewById(R.id.bt_return);
  70. tv_title = findViewById(R.id.tv_title);
  71. iv_icon = findViewById(R.id.iv_icon);
  72. tv_type = findViewById(R.id.tv_type);
  73. tv_title.setText("打印机连接");
  74. tv_type.setVisibility(View.VISIBLE);
  75. mDpi = SharedPreUtil.getInt(BlueToothPrintAct.this, "printDpi", 203);
  76. tv_type.setText(mDpi + "dpi");
  77. mPrintJson = getIntent().getStringExtra(Constants.KEY.BARCODE_PRINT_ARRAY);
  78. mRefreshImageView = findViewById(R.id.bluetooth_print_refresh_iv);
  79. mSwitchView = findViewById(R.id.bluetooth_print_sv);
  80. mRecyclerView = findViewById(R.id.bluetooth_print_rv);
  81. mRecyclerView.setLayoutManager(new LinearLayoutManager(BlueToothPrintAct.this));
  82. mRecyclerView.addItemDecoration(new RecyclerItemDecoration(1));
  83. mDpiList = new ArrayList<>();
  84. isConnected = (SharedPreUtil.getInt(BlueToothPrintAct.this, "printConnect", 0) == 1);
  85. mOldAddress = SharedPreUtil.getString(BlueToothPrintAct.this, "printAddress", "");
  86. }
  87. @Override
  88. protected void initEvents() {
  89. bt_return.setOnClickListener(new View.OnClickListener() {
  90. @Override
  91. public void onClick(View v) {
  92. finish();
  93. }
  94. });
  95. mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  96. @Override
  97. public void onClick(View view) {
  98. if (connectHelper.isOpenBluetooth()) {
  99. mRefreshImageView.setAnimation(getImgAnimation());
  100. mRefreshImageView.startAnimation(getImgAnimation());
  101. connectHelper.searchDevices();
  102. }
  103. }
  104. });
  105. mDpiList.add(152);
  106. mDpiList.add(203);
  107. mDpiList.add(300);
  108. mDpiList.add(600);
  109. tv_type.setOnClickListener(new View.OnClickListener() {
  110. @Override
  111. public void onClick(View v) {
  112. if (mMenuView == null) {
  113. mMenuView = View.inflate(BlueToothPrintAct.this, R.layout.pop_common_list_menu, null);
  114. }
  115. if (mMenuRecyclerView == null) {
  116. mMenuRecyclerView = mMenuView.findViewById(R.id.common_list_menu_rv);
  117. mMenuRecyclerView.setLayoutManager(new LinearLayoutManager(BlueToothPrintAct.this));
  118. mMenuRecyclerView.addItemDecoration(new RecyclerItemDecoration(1));
  119. }
  120. if (mMenuAdapter == null) {
  121. mMenuAdapter = new BaseQuickAdapter<Integer, BaseViewHolder>(R.layout.item_common_list_menu, mDpiList) {
  122. @Override
  123. protected void convert(BaseViewHolder helper, Integer item) {
  124. helper.setText(R.id.item_common_list_menu_btn, item + "dpi");
  125. }
  126. };
  127. mMenuRecyclerView.setAdapter(mMenuAdapter);
  128. mMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
  129. @Override
  130. public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
  131. closeMenuPopupWindow();
  132. mDpi = mDpiList.get(position);
  133. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printDpi", mDpi);
  134. tv_type.setText(mDpi + "dpi");
  135. }
  136. });
  137. }
  138. if (mMenuPopupWindow == null) {
  139. mMenuPopupWindow = new PopupWindow(mMenuView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
  140. mMenuPopupWindow.setBackgroundDrawable(new BitmapDrawable());
  141. mMenuPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
  142. @Override
  143. public void onDismiss() {
  144. closeMenuPopupWindow();
  145. }
  146. });
  147. }
  148. CommonUtil.setBackgroundAlpha(BlueToothPrintAct.this, 0.5f);
  149. mMenuPopupWindow.showAsDropDown(tv_type);
  150. }
  151. });
  152. }
  153. @Override
  154. protected void initDatas() {
  155. if (Build.VERSION.SDK_INT >= 6.0) {
  156. try {
  157. AndPermission.with(BlueToothPrintAct.this)
  158. .runtime()
  159. .permission(Permission.Group.LOCATION)
  160. .onGranted(new Action<List<String>>() {
  161. @Override
  162. public void onAction(List<String> data) {
  163. initHelper();
  164. }
  165. })
  166. .start();
  167. } catch (Exception e) {
  168. e.printStackTrace();
  169. }
  170. } else {
  171. initHelper();
  172. }
  173. }
  174. private void closeMenuPopupWindow() {
  175. if (mMenuPopupWindow != null) {
  176. mMenuPopupWindow.dismiss();
  177. mMenuPopupWindow = null;
  178. CommonUtil.setBackgroundAlpha(BlueToothPrintAct.this, 1f);
  179. }
  180. }
  181. private void initHelper() {
  182. connectHelper = new ConnectHelper(BlueToothPrintAct.this);
  183. connectHelper.setConnectListener(new ConnectHelper.ConnectListener() {
  184. @Override
  185. public void onDeviceChange(int state, BluetoothDevice device) {
  186. try {
  187. List<BluetoothDevice> models = mBluetoothAdapter.getModels();
  188. boolean hasConflict = false;
  189. if (!ListUtils.isEmpty(models)) {
  190. for (int i = 0; i < models.size(); i++) {
  191. BluetoothDevice model = models.get(i);
  192. if (model.getAddress().equals(device.getAddress())) {
  193. if (model.getBondState() != device.getBondState()) {
  194. models.remove(i);
  195. models.add(0, device);
  196. }
  197. hasConflict = true;
  198. break;
  199. }
  200. }
  201. }
  202. if (!hasConflict) {
  203. if (models == null) {
  204. models = new ArrayList<>();
  205. }
  206. if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
  207. models.add(0, device);
  208. } else {
  209. models.add(device);
  210. }
  211. }
  212. setAdapter(models);
  213. } catch (Exception e) {
  214. e.printStackTrace();
  215. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "蓝牙设备搜索异常,请重新搜索");
  216. }
  217. }
  218. @Override
  219. public void bindResult(int portOpen, BluetoothDevice device) {
  220. progressDialog.dismiss();
  221. if (portOpen == -11) {
  222. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印机连接异常");
  223. isConnected = false;
  224. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printConnect", 0);
  225. } else if (portOpen == -1) {
  226. mRetryCount++;
  227. if (mRetryCount > 3) {
  228. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印机连接失败,请检查打印机是否启动");
  229. isConnected = false;
  230. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printConnect", 0);
  231. mRetryCount = 0;
  232. } else {
  233. connectHelper.toConnectDeviceHY(device);
  234. }
  235. } else {
  236. // TODO: 2018/12/24 执行打印操作
  237. mRetryCount = 0;
  238. isConnected = true;
  239. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printConnect", 1);
  240. mOldAddress = device.getAddress();
  241. SharedPreUtil.saveString(BlueToothPrintAct.this, "printAddress", mOldAddress);
  242. printEvent();
  243. }
  244. }
  245. @Override
  246. public void onFinished() {
  247. mRefreshImageView.setAnimation(null);
  248. }
  249. });
  250. Set<BluetoothDevice> devices = connectHelper.getBondedDevices();
  251. List<BluetoothDevice> models = new ArrayList<>();
  252. if (!ListUtils.isEmptyBlue(devices)) {
  253. for (BluetoothDevice device : devices) {
  254. models.add(device);
  255. }
  256. }
  257. setAdapter(models);
  258. mSwitchView.setChecked(connectHelper.isOpenBluetooth());
  259. mSwitchView.setOnCheckedChangeListener(mOnCheckedChangeListener);
  260. }
  261. private void printEvent() {
  262. if (isPrinting) {
  263. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "正在打印中,请勿重复操作");
  264. return;
  265. }
  266. isPrinting = true;
  267. if (FastjsonUtil.validate(mPrintJson)) {
  268. JSONArray printArray = JSON.parseArray(mPrintJson);
  269. if (printArray != null && printArray.size() > 0) {
  270. boolean isFail = false;
  271. for (int i = 0; i < printArray.size(); i++) {
  272. JSONObject printObject = printArray.getJSONObject(i);
  273. int printResult = PrintUtils.printBar(BlueToothPrintAct.this, printObject.toJSONString(), mDpi, null);
  274. if (printResult <= 0) {
  275. isFail = true;
  276. }
  277. }
  278. if (isFail) {
  279. isConnected = false;
  280. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printConnect", 0);
  281. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印失败,请确定打印机是否正常");
  282. } else {
  283. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印成功");
  284. getSupportFragmentManager().popBackStack();
  285. }
  286. } else {
  287. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印失败,条码数据为空");
  288. }
  289. } else {
  290. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "打印失败,条码数据为空");
  291. }
  292. isPrinting = false;
  293. }
  294. private Animation getImgAnimation() {
  295. if (mRotateAnimation == null) {
  296. mRotateAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
  297. LinearInterpolator lin = new LinearInterpolator();
  298. mRotateAnimation.setInterpolator(lin);
  299. mRotateAnimation.setDuration(1000);//设置动画持续时间
  300. mRotateAnimation.setRepeatCount(-1);//设置重复次数
  301. mRotateAnimation.setFillAfter(true);//动画执行完后是否停留在执行完的状态
  302. mRotateAnimation.setStartOffset(10);//执行前的等待时间
  303. }
  304. return mRotateAnimation;
  305. }
  306. private void setAdapter(List<BluetoothDevice> models) {
  307. List<BluetoothDevice> printDevices = new ArrayList<>();
  308. if (!ListUtils.isEmpty(models)) {
  309. for (int i = 0; i < models.size(); i++) {
  310. BluetoothDevice bluetoothDevice = models.get(i);
  311. if (bluetoothDevice != null && bluetoothDevice.getBluetoothClass().getDeviceClass() == ConnectHelper.PRINT_TYPE) {
  312. printDevices.add(bluetoothDevice);
  313. }
  314. }
  315. }
  316. if (mBluetoothAdapter == null) {
  317. mBluetoothAdapter = new BluetoothAdapter(BlueToothPrintAct.this, printDevices);
  318. mBluetoothAdapter.setOnSendListener(mOnSendListener);
  319. mRecyclerView.setAdapter(mBluetoothAdapter);
  320. } else {
  321. mBluetoothAdapter.setModels(printDevices);
  322. }
  323. }
  324. private BluetoothAdapter.OnSendListener mOnSendListener = new BluetoothAdapter.OnSendListener() {
  325. @Override
  326. public void send(final BluetoothDevice device) {
  327. //TODO 对指定设备发送消息(必须先连接)
  328. /*AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
  329. builder.setTitle("选择连接类型");
  330. final String[] str = {"ESP机型", "汉印打印机"};
  331. builder.setSingleChoiceItems(str, -1, new DialogInterface.OnClickListener() {
  332. @Override
  333. public void onClick(DialogInterface dialog, int which) {
  334. //客户点击后,对话框记得消失
  335. dialog.dismiss();
  336. if (which == 0) {
  337. //ESC机型
  338. boolean bindOk = connectHelper.toConnectDevice(device);
  339. if (bindOk) {
  340. }
  341. } else {
  342. //汉印打印机
  343. connectHelper.toConnectDeviceHY(device);
  344. }
  345. }
  346. }
  347. );
  348. builder.show();*/
  349. String newAddress = device.getAddress();
  350. if (!TextUtils.isEmpty(newAddress) && newAddress.equals(mOldAddress)) {
  351. if (isConnected) {
  352. printEvent();
  353. } else {
  354. mRetryCount = 0;
  355. progressDialog.show();
  356. connectHelper.toConnectDeviceHY(device);
  357. }
  358. } else {
  359. mRetryCount = 0;
  360. isConnected = false;
  361. SharedPreUtil.saveInt(BlueToothPrintAct.this, "printConnect", 0);
  362. progressDialog.show();
  363. connectHelper.toConnectDeviceHY(device);
  364. }
  365. }
  366. @Override
  367. public void itemClick(BluetoothDevice device) {
  368. connectHelper.toConnectDevice(device);
  369. }
  370. };
  371. @Override
  372. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  373. super.onActivityResult(requestCode, resultCode, data);
  374. if (requestCode == REQUEST_ENABLE_BT) {
  375. mSwitchView.setOnCheckedChangeListener(null);
  376. if (resultCode == RESULT_OK) {
  377. mSwitchView.setChecked(true);
  378. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "蓝牙开启成功");
  379. } else {
  380. mSwitchView.setChecked(false);
  381. CommonUtil.toastNoRepeat(BlueToothPrintAct.this, "蓝牙开启失败");
  382. }
  383. mSwitchView.setOnCheckedChangeListener(mOnCheckedChangeListener);
  384. }
  385. }
  386. private SwitchView.OnCheckedChangeListener mOnCheckedChangeListener = new SwitchView.OnCheckedChangeListener() {
  387. @Override
  388. public void onCheckedChanged(SwitchView switchView, boolean b) {
  389. if (b) {
  390. connectHelper.openBluetooth(REQUEST_ENABLE_BT);
  391. } else {
  392. connectHelper.closeBluetooth();
  393. }
  394. }
  395. };
  396. @Override
  397. protected void onDestroy() {
  398. super.onDestroy();
  399. if (connectHelper != null) {
  400. connectHelper.onDestroy();
  401. }
  402. }
  403. }