MainActivity.java 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. package com.naz.sdkdemo;
  2. import android.Manifest;
  3. import android.annotation.SuppressLint;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothGatt;
  6. import android.bluetooth.BluetoothGattCharacteristic;
  7. import android.bluetooth.BluetoothGattService;
  8. import android.content.ContentValues;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.pm.PackageManager;
  12. import android.location.LocationManager;
  13. import android.os.Build;
  14. import android.os.Environment;
  15. import android.provider.MediaStore;
  16. import android.text.TextUtils;
  17. import android.util.Log;
  18. import android.view.KeyEvent;
  19. import android.view.View;
  20. import android.webkit.JavascriptInterface;
  21. import android.widget.Button;
  22. import android.widget.LinearLayout;
  23. import android.widget.Toast;
  24. import com.clj.fastble.BleManager;
  25. import com.clj.fastble.callback.BleGattCallback;
  26. import com.clj.fastble.callback.BleNotifyCallback;
  27. import com.clj.fastble.callback.BleScanCallback;
  28. import com.clj.fastble.data.BleDevice;
  29. import com.clj.fastble.exception.BleException;
  30. import com.clj.fastble.scan.BleScanRuleConfig;
  31. import com.clj.fastble.utils.HexUtil;
  32. import com.google.common.util.concurrent.ListenableFuture;
  33. import com.google.gson.Gson;
  34. import com.google.gson.reflect.TypeToken;
  35. import com.naz.sdkdemo.activity.ble.comm.ObserverManager;
  36. import com.naz.sdkdemo.base.BaseActivity;
  37. import com.naz.sdkdemo.bean.PrintModule;
  38. import com.naz.sdkdemo.bean.PrintModule2;
  39. import com.naz.sdkdemo.bean.PrintModule3;
  40. import com.naz.sdkdemo.helper.SerialPortManager;
  41. import com.naz.sdkdemo.http.ApiHelper;
  42. import com.naz.sdkdemo.utils.MyTools;
  43. import com.naz.sdkdemo.weight.UserCache;
  44. import com.tencent.smtt.export.external.interfaces.WebResourceError;
  45. import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
  46. import com.tencent.smtt.sdk.WebSettings;
  47. import com.tencent.smtt.sdk.WebView;
  48. import com.tencent.smtt.sdk.WebViewClient;
  49. import net.posprinter.IConnectListener;
  50. import net.posprinter.IDeviceConnection;
  51. import net.posprinter.POSConnect;
  52. import net.posprinter.TSPLConst;
  53. import net.posprinter.TSPLPrinter;
  54. import java.io.File;
  55. import java.io.UnsupportedEncodingException;
  56. import java.lang.reflect.Method;
  57. import java.lang.reflect.Type;
  58. import java.util.ArrayList;
  59. import java.util.List;
  60. import java.util.concurrent.ExecutionException;
  61. import java.util.concurrent.ExecutorService;
  62. import java.util.concurrent.Executors;
  63. import androidx.annotation.NonNull;
  64. import androidx.camera.core.CameraSelector;
  65. import androidx.camera.core.ImageCapture;
  66. import androidx.camera.core.ImageCaptureException;
  67. import androidx.camera.core.Preview;
  68. import androidx.camera.lifecycle.ProcessCameraProvider;
  69. import androidx.core.app.ActivityCompat;
  70. import androidx.core.content.ContextCompat;
  71. import androidx.lifecycle.LifecycleOwner;
  72. import static net.posprinter.TSPLConst.FNT_SIMPLIFIED_CHINESE;
  73. import static net.posprinter.TSPLConst.ROTATION_90;
  74. public class MainActivity extends BaseActivity {
  75. private final String TAG = "HomeActivity";
  76. private WebView mWebView;
  77. private LinearLayout ll_nonet;
  78. private LinearLayout ll_web;
  79. private Button printBtn;
  80. private Button connectBtn;
  81. private Button connectLight;
  82. private Button turnOnLight;
  83. private Button closeLight;
  84. private TSPLPrinter printer;
  85. String savePath;
  86. private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
  87. private ProcessCameraProvider cameraProvider;
  88. private ImageCapture imageCapture;
  89. private String bleName;
  90. private int code=0;//0默认值,1未搜索到设备,2连接失败,3连接成功,4断开了,5打开通知失败,6打开通知成功
  91. @Override
  92. protected int getLayoutResId() {
  93. return R.layout.activity_home_web;
  94. }
  95. @Override
  96. protected void initView() {
  97. ll_nonet = findViewById(R.id.ll_nonet);
  98. ll_web = findViewById(R.id.ll_web);
  99. mWebView = findViewById(R.id.webview);
  100. checkNet();
  101. findViewById(R.id.bt_ref).setOnClickListener(new View.OnClickListener(){
  102. @Override
  103. public void onClick(View v) {
  104. getUrl();
  105. }
  106. });
  107. getUrl();
  108. WebSettings ws = mWebView.getSettings();
  109. // 网页内容的宽度是否可大于WebView控件的宽度
  110. ws.setLoadWithOverviewMode(false);
  111. // 保存表单数据
  112. ws.setSaveFormData(true);
  113. // 是否应该支持使用其屏幕缩放控件和手势缩放
  114. ws.setSupportZoom(true);
  115. ws.setBuiltInZoomControls(true);
  116. ws.setDisplayZoomControls(false);
  117. // 启动应用缓存
  118. ws.setAppCacheEnabled(true);
  119. // 设置缓存模式
  120. ws.setCacheMode(WebSettings.LOAD_DEFAULT);
  121. // setDefaultZoom api19被弃用
  122. // 设置此属性,可任意比例缩放。
  123. ws.setUseWideViewPort(true);
  124. // 不缩放
  125. mWebView.setInitialScale(100);
  126. mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
  127. // 告诉WebView启用JavaScript执行。默认的是false。
  128. ws.setJavaScriptEnabled(true);
  129. // 页面加载好以后,再放开图片
  130. ws.setBlockNetworkImage(false);
  131. // 使用localStorage则必须打开
  132. ws.setDomStorageEnabled(true);
  133. // WebView是否新窗口打开(加了后可能打不开网页)
  134. ws.setSupportMultipleWindows(true);
  135. // String systemUserAgent = MyTools.getUserAgent(ws, getApplicationContext());
  136. // ws.setUserAgentString(systemUserAgent + "Zuyu_Android");
  137. ws.setAllowContentAccess(true);
  138. ws.setJavaScriptCanOpenWindowsAutomatically(true);
  139. ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
  140. /** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用) */
  141. ws.setTextZoom(100);
  142. aIn = new AndroidInterface();
  143. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  144. // 允许javascript出错
  145. try {
  146. Method method = Class.forName("android.webkit.WebView").
  147. getMethod("setWebContentsDebuggingEnabled", Boolean.TYPE);
  148. if (method != null) {
  149. method.setAccessible(true);
  150. method.invoke(null, true);
  151. }
  152. } catch (Exception e) {
  153. // do nothing
  154. }
  155. }
  156. mWebView.addJavascriptInterface(aIn, "androidJs");
  157. mWebView.setWebViewClient(new WebViewClient(){
  158. @Override
  159. public void onPageFinished(WebView view, String url) {
  160. super.onPageFinished(view, url);
  161. ll_nonet.setVisibility(View.GONE);
  162. ll_web.setVisibility(View.VISIBLE);
  163. }
  164. @Override
  165. public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
  166. if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) { // 4.0以上必须要加
  167. view.loadUrl(mUrl);
  168. return true;
  169. }
  170. return false;
  171. }
  172. @Override
  173. public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
  174. super.onReceivedError(view, request, error);
  175. Log.e("----------->","------->request="+request);
  176. Log.e("----------->","------->error="+error);
  177. }
  178. });
  179. printBtn = findViewById(R.id.print);
  180. printBtn.setOnClickListener(new View.OnClickListener() {
  181. @Override
  182. public void onClick(View v) {
  183. // String json = "[{\"created_date_lt\":\"2024-03-09T10:05:07.000Z\",\"created_date\":\"2024-03-09T10:05:07.632Z\",\"last_modified_by_show\":\"李晓\",\"device_code\":\"DV00001\",\"material_code\":\"40010101000001\",\"last_modified_by\":\"3\",\"unit_code_show\":\"张\",\"bus_type_dk\":\"SUPPLIER\",\"created_by\":\"3\",\"unit_code\":\"ST\",\"dynamic_form_value_id\":\"554243331748798464\",\"supplier_code_show\":\"湖北鹰冠新型材料科技有限公司\",\"device_code_show\":\"测试设备\",\"belong_org\":\"S000233\",\"bus_type_dk_show\":\"工厂\",\"created_by_show\":\"李晓\",\"id\":\"554243331786547200\",\"supplier_code\":\"S000233\",\"main_table_id\":null,\"last_modified_date_lt\":\"2024-03-09T10:05:07.000Z\",\"material_code_show\":\"尊贵免漆板E0小标\",\"qty\":1984,\"specs\":null,\"box_code\":\"CK00001\",\"request_id\":null,\"detail_table_id\":null,\"last_modified_date\":\"2024-03-09T10:05:07.637Z\",\"box_code_show\":\"设备仓\",\"in_stock_qty\":496,\"use_qty\":-1488,\"safe_stock_qty\":1000,\"min_stock_qty\":500,\"is_choose\":true,\"old_roll_qr_code\":\"\",\"roll_qr_code\":\"1711532698000\"}]";
  184. // Gson gson=new Gson();
  185. // Type type = new TypeToken<List<PrintModule3>>(){}.getType();
  186. // List<PrintModule3> data = gson.fromJson(json, type);
  187. // if (data == null) {
  188. // return;
  189. // }
  190. // startPrint3(data);
  191. String json = "[{\n" +
  192. "\t\"now_date\": \"2024-04-14\",\n" +
  193. "\t\"box_date\": \"2024-03-27T08:55:01.569Z\",\n" +
  194. "\t\"delivery_flag\": 0,\n" +
  195. "\t\"status_dk_show\": \"已包\",\n" +
  196. "\t\"status_dk\": \"PACKAGED\",\n" +
  197. "\t\"print_flag\": 0,\n" +
  198. "\t\"no\": \"BZ2024032700001\",\n" +
  199. "\t\"device_code_show\": \"测试设备\",\n" +
  200. "\t\"device_code\": \"DV00001\",\n" +
  201. "\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
  202. "\t\"id\": \"560748673403850752\",\n" +
  203. "\t\"main_table_id\": null,\n" +
  204. "\t\"request_id\": null,\n" +
  205. "\t\"box_order_product\": {\n" +
  206. "\t\t\"customer_no\": \"C00912\",\n" +
  207. "\t\t\"process_title_two\": null,\n" +
  208. "\t\t\"customer_name\": \"信息中心客户-测试\",\n" +
  209. "\t\t\"color_two\": null,\n" +
  210. "\t\t\"dealer_name\": \"信息中心经销商-测试\",\n" +
  211. "\t\t\"order_item_id\": \"553451940644175872\",\n" +
  212. "\t\t\"process_title\": \"同步\",\n" +
  213. "\t\t\"material_title\": \"大王椰1800尊贵型E0指接香杉木-银盾抗菌生态免漆板W\",\n" +
  214. "\t\t\"order_no\": \"SO202403070001\",\n" +
  215. "\t\t\"box_num\": 50,\n" +
  216. "\t\t\"dealer_no\": \"C00911\",\n" +
  217. "\t\t\"color\": \"春华秋实\",\n" +
  218. "\t\t\"material_no\": \"BC170202000001\",\n" +
  219. "\t\t\"material_size\": \"3300-4\",\n" +
  220. "\t\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
  221. "\t\t\"id\": \"560748673416433664\",\n" +
  222. "\t\t\"main_table_id\": \"560748673403850752\",\n" +
  223. "\t\t\"request_id\": null\n" +
  224. "\t},\n" +
  225. "\t\"is_choose\": true\n" +
  226. "}]";
  227. Gson gson=new Gson();
  228. Type type = new TypeToken<List<PrintModule2>>(){}.getType();
  229. List<PrintModule2> data = gson.fromJson(json, type);
  230. if (data == null) {
  231. return;
  232. }
  233. startPrint2(data);
  234. }
  235. });
  236. connectBtn = findViewById(R.id.connect);
  237. connectBtn.setOnClickListener(new View.OnClickListener() {
  238. @Override
  239. public void onClick(View v) {
  240. connectUSB(searchUsb());
  241. }
  242. });
  243. connectLight = findViewById(R.id.connect2);
  244. turnOnLight = findViewById(R.id.light);
  245. connectLight.setOnClickListener(new View.OnClickListener() {
  246. @Override
  247. public void onClick(View v) {
  248. toConnectLight(UserCache.getSerialName());
  249. }
  250. });
  251. turnOnLight.setOnClickListener(new View.OnClickListener() {
  252. @Override
  253. public void onClick(View v) {
  254. if (serialPortManager != null){
  255. serialPortManager.turnOnLight(6);
  256. }
  257. }
  258. });
  259. closeLight = findViewById(R.id.closeLight);
  260. closeLight.setOnClickListener(new View.OnClickListener() {
  261. @Override
  262. public void onClick(View v) {
  263. if (serialPortManager!=null){
  264. serialPortManager.close();
  265. serialPortManager = null;
  266. }
  267. }
  268. });
  269. findViewById(R.id.take_photo).setOnClickListener(new View.OnClickListener(){
  270. @Override
  271. public void onClick(View v) {
  272. Log.e("-------->","------->path="+getImagePath("123.jpg"));
  273. savePicture(new File(getImagePath("123.jpg")), "ceshi", "202119");
  274. // new Handler().postDelayed(new Runnable() {
  275. // @Override
  276. // public void run() {
  277. // savePicture(new File(getImagePath("234.jpg")), "ceshi", "202119");
  278. // }
  279. // }, 20000);
  280. // new Handler().postDelayed(new Runnable() {
  281. // @Override
  282. // public void run() {
  283. // savePicture(new File(getImagePath("345.jpg")), "ceshi", "202119");
  284. // }
  285. // }, 30000);
  286. // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
  287. }
  288. });
  289. findViewById(R.id.start_scan).setOnClickListener(new View.OnClickListener(){
  290. @Override
  291. public void onClick(View v) {
  292. checkPermissions("dawangye");
  293. // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
  294. }
  295. });
  296. findViewById(R.id.close_scan).setOnClickListener(new View.OnClickListener(){
  297. @Override
  298. public void onClick(View v) {
  299. closeScan();
  300. // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
  301. }
  302. });
  303. Log.e("------->","-------->"+UserCache.getSerialName());
  304. }
  305. private AndroidInterface aIn;
  306. private class AndroidInterface {
  307. @JavascriptInterface
  308. public void takePhoto(String path, String name) {
  309. Log.e(TAG, "takePhoto");
  310. toTakePhoto(path, name);
  311. }
  312. @JavascriptInterface
  313. public void refreshData() {
  314. Log.e(TAG, "clearCache");
  315. mWebView.clearCache(false);
  316. mWebView.reload();
  317. }
  318. //打印
  319. @JavascriptInterface
  320. public void printF(String json) {
  321. Log.e(TAG, "printF json"+json);
  322. Gson gson=new Gson();
  323. Type type = new TypeToken<List<PrintModule>>(){}.getType();
  324. List<PrintModule> data = gson.fromJson(json, type);
  325. if (data == null) {
  326. return;
  327. }
  328. startPrint(data);
  329. }
  330. @JavascriptInterface
  331. public void printF2(String json) {
  332. Log.e(TAG, "printF2 json"+json);
  333. Gson gson=new Gson();
  334. Type type = new TypeToken<List<PrintModule2>>(){}.getType();
  335. List<PrintModule2> data = gson.fromJson(json, type);
  336. if (data == null) {
  337. return;
  338. }
  339. startPrint2(data);
  340. }
  341. @JavascriptInterface
  342. public void printF3(String json) {
  343. Log.e(TAG, "printF3 json"+json);
  344. Gson gson=new Gson();
  345. Type type = new TypeToken<List<PrintModule3>>(){}.getType();
  346. List<PrintModule3> data = gson.fromJson(json, type);
  347. if (data == null) {
  348. return;
  349. }
  350. startPrint3(data);
  351. }
  352. @JavascriptInterface
  353. public void startScan(String name) {
  354. Log.e(TAG, "startScan name"+name);
  355. checkPermissions(name);
  356. }
  357. @JavascriptInterface
  358. public void closeScan() {
  359. Log.e(TAG, "closeScan");
  360. closeScan();
  361. }
  362. @JavascriptInterface
  363. public void openCamera() {
  364. Log.e(TAG, "openCamera");
  365. toOpenCamera();
  366. }
  367. @JavascriptInterface
  368. public void closeCamera() {
  369. Log.e(TAG, "closeCamera");
  370. toCloseCamera();
  371. }
  372. @JavascriptInterface
  373. public void openPrinter() {
  374. Log.e(TAG, "openPrinter");
  375. connectUSB(searchUsb());
  376. }
  377. @JavascriptInterface
  378. public void closePrinter() {
  379. Log.e(TAG, "closePrinter");
  380. closeUSB();
  381. }
  382. @JavascriptInterface
  383. public void connectLight(String name) {
  384. Log.e(TAG, "connectLight");
  385. toConnectLight(name);
  386. }
  387. @JavascriptInterface
  388. public void controlLight(int address, int type) {
  389. Log.e(TAG, "openLight"+"address="+address+",type="+type);
  390. if (serialPortManager != null){
  391. serialPortManager.turnOnLight(address, type);
  392. }
  393. }
  394. @JavascriptInterface
  395. public void disConnectLight() {
  396. Log.e(TAG, "closeLight");
  397. if (serialPortManager!=null){
  398. serialPortManager.close();
  399. serialPortManager = null;
  400. }
  401. }
  402. @JavascriptInterface
  403. public void getPort() {
  404. Log.e(TAG, "getPort");
  405. mWebView.loadUrl("javascript:getPort('" + UserCache.getSerialPortName() + "')");
  406. }
  407. }
  408. private void toCloseCamera() {
  409. if (cameraProvider!=null){
  410. cameraProvider.unbindAll();
  411. }
  412. }
  413. private void toOpenCamera() {
  414. // 请求 CameraProvider
  415. cameraProviderFuture = ProcessCameraProvider.getInstance(this);
  416. //检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
  417. cameraProviderFuture.addListener(() -> {
  418. try {
  419. ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
  420. bindPreview(cameraProvider);
  421. } catch (ExecutionException | InterruptedException e) {
  422. // No errors need to be handled for this Future.
  423. // This should never be reached.
  424. }
  425. }, ContextCompat.getMainExecutor(this));
  426. }
  427. private void toTakePhoto(String path, String name) {
  428. Log.e("-------->","------>toTakePhoto");
  429. long timeStamp = System.currentTimeMillis();
  430. savePath = timeStamp+".jpg";
  431. // 通过 ContentValues 对象设置文件名和文件类型
  432. ContentValues contentValues = new ContentValues();
  433. contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, savePath);
  434. contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
  435. File dir = new File(Environment.getExternalStorageDirectory() + "/camera/");
  436. if (!dir.exists()) {
  437. dir.mkdirs();
  438. }
  439. //创建文件
  440. File file = new File(dir,savePath);
  441. ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
  442. imageCapture.takePicture(
  443. // 第一个参数 OutputFileOptions 指定了照片保存的位置和格式等信息。
  444. outputFileOptions,
  445. // 第二个参数 Executor 指定了保存照片时要运行的线程。
  446. ContextCompat.getMainExecutor(this),
  447. // 第三个参数 OnImageSavedCallback 指定了保存照片完成后的回调函数,可以在其中进行一些提示或其他操作。
  448. new ImageCapture.OnImageSavedCallback() {
  449. @SuppressLint("RestrictedApi")
  450. @Override
  451. public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
  452. Log.e("-------->","------>savePath="+outputFileResults.getSavedUri().getPath());
  453. Log.e("-------->","------>保存成功");
  454. // Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
  455. savePicture(file, path, name);
  456. mWebView.loadUrl("javascript:uploadPhotoPath('" + outputFileOptions.getFile().getAbsolutePath() + "')");
  457. }
  458. @Override
  459. public void onError(@NonNull ImageCaptureException exception) {
  460. Log.e("----------->","------->"+exception.getMessage());
  461. // Toast.makeText(MainActivity.this, "Error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
  462. }
  463. });
  464. }
  465. boolean isStart = false;
  466. ExecutorService fixedThreadPool;
  467. private void savePicture(File file, String path, String name) {
  468. if (!isStart){
  469. isStart = true;
  470. int numberOfCores = Runtime.getRuntime().availableProcessors();
  471. Log.i("--------->", "-------->cpu核心数" + numberOfCores);
  472. fixedThreadPool = Executors.newFixedThreadPool(2*numberOfCores+1);
  473. }
  474. try {
  475. fixedThreadPool.execute(new Runnable() {
  476. @Override
  477. public void run() {
  478. Log.i("--------->", "-------->uploadPicture" + file.getAbsolutePath());
  479. ApiHelper.uploadPicture(MainActivity.this, file, path, name);
  480. }
  481. });
  482. }catch (Exception e){
  483. e.printStackTrace();
  484. }
  485. }
  486. private void checkNet() {
  487. if (!MyTools.isNetworkAvailable(getApplicationContext())) {
  488. ll_nonet.setVisibility(View.VISIBLE);
  489. ll_web.setVisibility(View.GONE);
  490. } else {
  491. ll_nonet.setVisibility(View.GONE);
  492. ll_web.setVisibility(View.VISIBLE);
  493. }
  494. }
  495. String mUrl = "https://dwytb.qingyaokeji.com/index.html#/";
  496. private void getUrl() {
  497. mWebView.loadUrl(mUrl);
  498. }
  499. @Override
  500. public boolean onKeyDown(int keyCode, KeyEvent event) {
  501. if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
  502. mWebView.goBack();
  503. return true;
  504. }
  505. return super.onKeyDown(keyCode, event);
  506. }
  507. static int mPot = 8;//mm转像素8倍
  508. static int mWFont = 24;//字体宽度
  509. static int mHFont = 24;//字体高度
  510. static int mPaperWidth = 78;//纸张宽度78mm
  511. static int mPaperHeight = 132;//纸张高度132mm
  512. static int fontSizeMultiple = 2;//字体倍数
  513. static int mOffsetY = 5;//打印开始点离左边的距离(Y轴),5mm
  514. static int mOffsetX = mPaperWidth-5;//打印开始点离上边的距离(X轴),5mm
  515. static int mFontWidth = mWFont * fontSizeMultiple;//文字的宽度
  516. static int mFontHeight = mHFont * fontSizeMultiple;//文字的高度
  517. static int mSpace = 4;//行列间隔-----5mm
  518. static int mTextSpace = 1;//换行间距----2mm
  519. static int mCodeSize = 30;//二维码宽高----30mm
  520. private void startPrint(List<PrintModule> data) {
  521. for (PrintModule module:data) {
  522. printer.sizeMm(mPaperWidth, mPaperHeight)
  523. .density(10)
  524. .reference(mPaperWidth*mPot, 0)
  525. .direction(TSPLConst.DIRECTION_FORWARD)
  526. .cls()
  527. .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号:")
  528. .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.no)
  529. .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称:");
  530. String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
  531. printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
  532. int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
  533. if (!TextUtils.isEmpty(productName[1])){
  534. currentHeight = currentHeight-mTextSpace*mPot;
  535. printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
  536. currentHeight = currentHeight-mFontHeight;
  537. }
  538. if (!TextUtils.isEmpty(productName[2])){
  539. currentHeight = currentHeight-mTextSpace*mPot;
  540. printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
  541. currentHeight = currentHeight-mFontHeight;
  542. }
  543. currentHeight = currentHeight-mSpace*mPot;
  544. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商:")
  545. .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.customer_name);
  546. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  547. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号:")
  548. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_no)
  549. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量:")
  550. .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_num);
  551. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  552. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色:")
  553. .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.decor_code_show);
  554. if (module.decor_two_code_show!=null){
  555. printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.decor_code_show)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.decor_two_code_show);
  556. }
  557. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  558. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺:")
  559. .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.craft_type_code_show);
  560. if (module.craft_type_two_code_show!=null){
  561. printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.craft_type_code_show)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.craft_type_two_code_show);
  562. }
  563. printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
  564. printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.box_no);
  565. printer.print();
  566. }
  567. }
  568. private void startPrint2(List<PrintModule2> data) {
  569. for (PrintModule2 module:data) {
  570. printer.sizeMm(mPaperWidth, mPaperHeight)
  571. .density(10)
  572. .reference(mPaperWidth*mPot, 0)
  573. .direction(TSPLConst.DIRECTION_FORWARD)
  574. .cls()
  575. .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号:")
  576. .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.order_no)
  577. .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称:");
  578. String[] productName = getStrs(module.box_order_product.material_title, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
  579. printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
  580. int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
  581. if (!TextUtils.isEmpty(productName[1])){
  582. currentHeight = currentHeight-mTextSpace*mPot;
  583. printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
  584. currentHeight = currentHeight-mFontHeight;
  585. }
  586. if (!TextUtils.isEmpty(productName[2])){
  587. currentHeight = currentHeight-mTextSpace*mPot;
  588. printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
  589. currentHeight = currentHeight-mFontHeight;
  590. }
  591. currentHeight = currentHeight-mSpace*mPot;
  592. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商:")
  593. .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.customer_name);
  594. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  595. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号:")
  596. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.no)
  597. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量:")
  598. .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.box_num);
  599. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  600. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色:")
  601. .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.color);
  602. if (module.box_order_product.color_two!=null){
  603. printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.box_order_product.color)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.color_two);
  604. }
  605. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  606. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺:")
  607. .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.process_title);
  608. if (module.box_order_product.process_title_two!=null){
  609. printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.box_order_product.process_title)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.process_title_two);
  610. }
  611. printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
  612. printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.no);
  613. printer.print();
  614. }
  615. }
  616. private void startPrint3(List<PrintModule3> data) {
  617. for (PrintModule3 module:data) {
  618. printer.sizeMm(mPaperWidth, mPaperHeight)
  619. .density(10)
  620. .reference(mPaperWidth*mPot, 0)
  621. .direction(TSPLConst.DIRECTION_FORWARD)
  622. .cls()
  623. .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_code_show);
  624. String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot);
  625. printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
  626. int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
  627. if (!TextUtils.isEmpty(productName[1])){
  628. currentHeight = currentHeight-mTextSpace*mPot;
  629. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
  630. }
  631. if (!TextUtils.isEmpty(productName[2])){
  632. currentHeight = currentHeight-mTextSpace*mPot-mFontHeight;
  633. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
  634. }
  635. currentHeight = currentHeight-mSpace*mPot;
  636. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "商标编码:")
  637. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.material_code);
  638. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  639. printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "余标:")
  640. .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.qty);
  641. printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.roll_qr_code), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.roll_qr_code);
  642. currentHeight = currentHeight-mFontHeight-mSpace*mPot;
  643. printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
  644. printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.roll_qr_code);
  645. printer.print();
  646. }
  647. }
  648. //选择相机并绑定生命周期和用例
  649. private void bindPreview(@NonNull ProcessCameraProvider cp) {
  650. this.cameraProvider=cp;
  651. Preview preview = new Preview.Builder()
  652. .build();
  653. @SuppressLint("UnsafeOptInUsageError")
  654. CameraSelector cameraSelector = new CameraSelector.Builder()
  655. .requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
  656. .build();
  657. // 创建一个 ImageCapture 对象,用于拍摄照片。
  658. // 设置拍照模式为最小化延迟模式,这意味着拍照时将尽可能快地捕获图像。
  659. imageCapture = new ImageCapture.Builder()
  660. .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
  661. // 设置JPEG的质量为85%
  662. .setJpegQuality(85)
  663. .build();
  664. cameraProvider.unbindAll();//解绑组件
  665. cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
  666. // preview.setSurfaceProvider(previewView.getSurfaceProvider());
  667. }
  668. public static int getStrLength(String xm){
  669. int xmLength = 0;
  670. for (int i = 0; i < xm.length(); i++) {
  671. char chr = xm.charAt(i);
  672. if (isChinese(chr)){
  673. xmLength+=(mWFont*fontSizeMultiple);
  674. }else {
  675. xmLength+=(mWFont*fontSizeMultiple/2);
  676. }
  677. }
  678. Log.e("------->","----->xmStrLength="+xmLength);
  679. return xmLength;
  680. }
  681. public static String[] getStrs(String xm, int maxLength){
  682. Log.e("------->","----->maxLength="+maxLength);
  683. String[] resultStrs = new String[3];
  684. int xmLength = 0;
  685. int xmIndex = 0;
  686. String xmStr1 = "", xmStr2 = "", xmStr3 = "";
  687. boolean isLn = false;
  688. for (int i = 0; i < xm.length(); i++) {
  689. char chr = xm.charAt(i);
  690. if (isChinese(chr)){
  691. xmLength+=(mWFont*fontSizeMultiple);
  692. }else {
  693. xmLength+=(mWFont*fontSizeMultiple/2);
  694. }
  695. if (!isLn){
  696. if (xmLength>maxLength){
  697. isLn = true;
  698. xmIndex = i;
  699. }
  700. }
  701. }
  702. Log.e("------->","----->index="+xmIndex);
  703. String str = xm;
  704. if (xmLength>maxLength){
  705. xmStr1 = str.substring(0, xmIndex);
  706. String xmStr = xm.substring(xmIndex);
  707. int xmLength2 = 0;
  708. int xmIndex2 = 0;
  709. boolean isLn2 = false;
  710. for (int i = 0; i < xmStr.length(); i++) {
  711. char chr = xmStr.charAt(i);
  712. if (isChinese(chr)){
  713. xmLength2+=24*fontSizeMultiple;
  714. }else {
  715. xmLength2+=12*fontSizeMultiple;
  716. }
  717. if (!isLn2){
  718. String str2 = xmStr;
  719. if (xmLength2>maxLength){
  720. isLn2 = true;
  721. xmIndex2 = i;
  722. xmStr2 = str2.substring(0, xmIndex2);
  723. xmStr3 = xmStr.substring(xmIndex2);
  724. }else{
  725. xmStr2 = str2;
  726. xmStr3 = "";
  727. }
  728. }
  729. }
  730. }else {
  731. xmStr1 = str;
  732. xmStr2 = "";
  733. xmStr3 = "";
  734. }
  735. Log.e("------->","----->xmStr1="+xmStr1);
  736. Log.e("------->","----->xmStr2="+xmStr2);
  737. Log.e("------->","----->xmStr3="+xmStr3);
  738. resultStrs[0] = xmStr1;
  739. resultStrs[1] = xmStr2;
  740. resultStrs[2] = xmStr3;
  741. return resultStrs;
  742. }
  743. public static boolean isChinese(char chr) {
  744. boolean isChinese = false;
  745. //if ((int)str[i] > 127)//判断是否是汉字
  746. if ((int)chr > 0x4E00 && (int)chr < 0x9FA5) {
  747. isChinese = true;
  748. } else {
  749. isChinese = false; ;
  750. }
  751. return isChinese;
  752. }
  753. public static String getImagePath(String imageName) {
  754. File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
  755. File imageFile = new File(picturesDir, imageName);
  756. return imageFile.exists() ? imageFile.getAbsolutePath() :"";
  757. }
  758. private static final int REQUEST_CODE_OPEN_GPS = 1;
  759. private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
  760. private void checkPermissions(String name) {
  761. bleName = name;
  762. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  763. if (!bluetoothAdapter.isEnabled()) {
  764. Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
  765. return;
  766. }
  767. String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
  768. List<String> permissionDeniedList = new ArrayList<>();
  769. for (String permission : permissions) {
  770. int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
  771. if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
  772. onPermissionGranted(permission);
  773. } else {
  774. permissionDeniedList.add(permission);
  775. }
  776. }
  777. if (!permissionDeniedList.isEmpty()) {
  778. Log.e("------->","----->checkPermissions permissionDeniedList="+permissionDeniedList);
  779. String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
  780. ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
  781. }
  782. }
  783. private void onPermissionGranted(String permission) {
  784. Log.e("------->","----->onPermissionGranted permission="+permission);
  785. switch (permission) {
  786. case Manifest.permission.ACCESS_FINE_LOCATION:
  787. setScanRule();
  788. startScan(bleName);
  789. // Log.e("------->","----->checkGPSIsOpen="+checkGPSIsOpen());
  790. // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
  791. // new AlertDialog.Builder(this)
  792. // .setTitle(R.string.notifyTitle)
  793. // .setMessage(R.string.gpsNotifyMsg)
  794. // .setNegativeButton(R.string.cancel,
  795. // new DialogInterface.OnClickListener() {
  796. // @Override
  797. // public void onClick(DialogInterface dialog, int which) {
  798. // finish();
  799. // }
  800. // })
  801. // .setPositiveButton(R.string.setting,
  802. // new DialogInterface.OnClickListener() {
  803. // @Override
  804. // public void onClick(DialogInterface dialog, int which) {
  805. // Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  806. // startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
  807. // }
  808. // })
  809. //
  810. // .setCancelable(false)
  811. // .show();
  812. // } else {
  813. // setScanRule();
  814. // startScan(bleName);
  815. // }
  816. break;
  817. }
  818. }
  819. //关闭蓝牙扫码器
  820. BleDevice mBleDevice;
  821. BluetoothGattCharacteristic mCharacteristic;
  822. private void closeScan(){
  823. if (mBleDevice!=null){
  824. if (BleManager.getInstance().isConnected(mBleDevice)) {
  825. BleManager.getInstance().disconnect(mBleDevice);
  826. }
  827. BleManager.getInstance().removeNotifyCallback(mBleDevice, mCharacteristic.getService().getUuid().toString());
  828. BleManager.getInstance().clearCharacterCallback(mBleDevice);
  829. BleManager.getInstance().removeConnectGattCallback(mBleDevice);
  830. }
  831. }
  832. @Override
  833. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  834. super.onActivityResult(requestCode, resultCode, data);
  835. if (requestCode == REQUEST_CODE_OPEN_GPS) {
  836. // if (checkGPSIsOpen()) {
  837. setScanRule();
  838. startScan(bleName);
  839. // }
  840. }
  841. }
  842. private boolean checkGPSIsOpen() {
  843. // LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  844. // if (locationManager == null)
  845. // return false;
  846. // return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  847. LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  848. boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  849. boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  850. return isGpsEnabled || isNetworkEnabled;
  851. }
  852. private void setScanRule() {
  853. BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
  854. .setScanTimeOut(10000) // 扫描超时时间,可选,默认10秒
  855. .build();
  856. BleManager.getInstance().initScanRule(scanRuleConfig);
  857. }
  858. //开始蓝牙扫码器
  859. private void startScan(String name) {
  860. // Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
  861. BleManager.getInstance().scan(new BleScanCallback() {
  862. @Override
  863. public void onScanStarted(boolean success) {
  864. }
  865. @Override
  866. public void onLeScan(BleDevice bleDevice) {
  867. super.onLeScan(bleDevice);
  868. }
  869. @Override
  870. public void onScanning(BleDevice bleDevice) {
  871. if ((name+"BLE").equals(bleDevice.getName())){
  872. // Toast.makeText(MainActivity.this, "名字匹配去链接", Toast.LENGTH_SHORT).show();
  873. if (!BleManager.getInstance().isConnected(bleDevice)) {
  874. BleManager.getInstance().cancelScan();
  875. connect(bleDevice);
  876. }
  877. }else {
  878. // Toast.makeText(MainActivity.this, "名字不匹配", Toast.LENGTH_SHORT).show();
  879. }
  880. }
  881. @Override
  882. public void onScanFinished(List<BleDevice> scanResultList) {
  883. boolean isScanSuccess = false;
  884. for (int i = 0; i < scanResultList.size(); i++) {
  885. BleDevice bleDevice = scanResultList.get(i);
  886. if ((name+"BLE").equals(bleDevice.getName())){
  887. isScanSuccess = true;
  888. }
  889. }
  890. // Toast.makeText(MainActivity.this, "扫描完成,是否成功="+isScanSuccess, Toast.LENGTH_SHORT).show();
  891. if (isScanSuccess){
  892. mWebView.loadUrl("javascript:responseCode('1')");
  893. }
  894. }
  895. });
  896. }
  897. private void connect(final BleDevice bleDevice) {
  898. BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
  899. @Override
  900. public void onStartConnect() {
  901. }
  902. @Override
  903. public void onConnectFail(BleDevice bleDevice, BleException exception) {
  904. Log.e("-------->","------>连接失败");
  905. // Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
  906. mWebView.loadUrl("javascript:responseCode('2')");
  907. }
  908. @Override
  909. public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
  910. Log.e("-------->","------>连接成功");
  911. // Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
  912. mBleDevice = bleDevice;
  913. mWebView.loadUrl("javascript:responseCode('3')");
  914. if (BleManager.getInstance().isConnected(bleDevice)) {
  915. BluetoothGattService bluetoothGattService = null;
  916. for (BluetoothGattService service : gatt.getServices()) {
  917. if (service.getUuid().toString().contains("0000feea")){
  918. bluetoothGattService = service;
  919. }
  920. }
  921. if (bluetoothGattService!=null){
  922. List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
  923. for (int i = 0; i < characteristics.size(); i++) {
  924. BluetoothGattCharacteristic characteristic = characteristics.get(i);
  925. if (characteristic.getUuid().toString().contains("00002aa1")){
  926. mCharacteristic = characteristic;
  927. BleManager.getInstance().notify(
  928. bleDevice,
  929. characteristic.getService().getUuid().toString(),
  930. characteristic.getUuid().toString(),
  931. new BleNotifyCallback() {
  932. @Override
  933. public void onNotifySuccess() {
  934. runOnUiThread(new Runnable() {
  935. @Override
  936. public void run() {
  937. // Toast.makeText(MainActivity.this, "打开通知成功", Toast.LENGTH_SHORT).show();
  938. Log.e("-------->","-------->打开通知成功");
  939. mWebView.loadUrl("javascript:responseCode('6')");
  940. }
  941. });
  942. }
  943. @Override
  944. public void onNotifyFailure(final BleException exception) {
  945. Log.e("-------->","------>打开通知失败");
  946. runOnUiThread(new Runnable() {
  947. @Override
  948. public void run() {
  949. // Toast.makeText(MainActivity.this, "连接通知失败", Toast.LENGTH_SHORT).show();
  950. mWebView.loadUrl("javascript:responseCode('5')");
  951. }
  952. });
  953. }
  954. @Override
  955. public void onCharacteristicChanged(byte[] data) {
  956. runOnUiThread(new Runnable() {
  957. @Override
  958. public void run() {
  959. // Log.e("-------->","-------->data="+(HexUtil.formatHexString(data, true)));
  960. Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(data, false))));
  961. // Toast.makeText(MainActivity.this, "接收数据="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))), Toast.LENGTH_SHORT).show();
  962. mWebView.loadUrl("javascript:responseData('"+(hexStringToGbk(HexUtil.formatHexString(data, false)))+"')");
  963. // Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))));
  964. // Log.e("-------->","-------->data="+(HexUtil.formatHexString(characteristic.getValue(), true)));
  965. }
  966. });
  967. }
  968. });
  969. }
  970. }
  971. }
  972. }
  973. }
  974. @Override
  975. public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
  976. mBleDevice = null;
  977. if (isActiveDisConnected) {
  978. Log.e("-------->","------>断开了");
  979. mWebView.loadUrl("javascript:responseCode('4')");
  980. } else {
  981. Log.e("-------->","------>连接断开");
  982. mWebView.loadUrl("javascript:responseCode('5')");
  983. ObserverManager.getInstance().notifyObserver(bleDevice);
  984. }
  985. }
  986. });
  987. }
  988. public String hexStringToGbk(String hexString) {
  989. byte[] bytes = new byte[hexString.length() / 2];
  990. for (int i = 0; i < hexString.length(); i += 2) {
  991. bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
  992. + Character.digit(hexString.charAt(i+1), 16));
  993. }
  994. try {
  995. return new String(bytes, "GBK");
  996. } catch (UnsupportedEncodingException e) {
  997. e.printStackTrace();
  998. return null;
  999. }
  1000. }
  1001. IDeviceConnection curConnect = null;
  1002. private void connectUSB(String pathName){
  1003. if (curConnect!=null){
  1004. curConnect.close();
  1005. }
  1006. curConnect = POSConnect.createDevice(POSConnect.DEVICE_TYPE_USB);
  1007. curConnect.connect(pathName, connectListener);
  1008. printer = new TSPLPrinter(curConnect);
  1009. }
  1010. public String searchUsb() {
  1011. List<String> usbNames = POSConnect.getUsbDevices(this);
  1012. // XToast.showToast("usbNames="+usbNames.size());
  1013. String ret = "";
  1014. if (usbNames.size()>0) {
  1015. ret = usbNames.get(0);
  1016. }
  1017. Log.e("-------->","------>ret="+ret);
  1018. return ret;
  1019. }
  1020. private void closeUSB() {
  1021. if (curConnect!=null){
  1022. curConnect.close();
  1023. }
  1024. }
  1025. private IConnectListener connectListener = new IConnectListener() {
  1026. @Override
  1027. public void onStatus(int code, String connInfo, String msg) {
  1028. switch (code){
  1029. case POSConnect.CONNECT_SUCCESS:
  1030. Log.e("-------->","------>CONNECT_SUCCESS");
  1031. mWebView.loadUrl("javascript:printerCode('1')");
  1032. break;
  1033. case POSConnect.CONNECT_FAIL:
  1034. Log.e("-------->","------>CONNECT_FAIL");
  1035. mWebView.loadUrl("javascript:printerCode('2')");
  1036. break;
  1037. case POSConnect.CONNECT_INTERRUPT:
  1038. Log.e("-------->","------>CONNECT_INTERRUPT");
  1039. mWebView.loadUrl("javascript:printerCode('3')");
  1040. break;
  1041. case POSConnect.SEND_FAIL:
  1042. Log.e("-------->","------>SEND_FAIL");
  1043. mWebView.loadUrl("javascript:printerCode('4')");
  1044. break;
  1045. case POSConnect.USB_DETACHED:
  1046. Log.e("-------->","------>USB_DETACHED");
  1047. mWebView.loadUrl("javascript:printerCode('5')");
  1048. break;
  1049. case POSConnect.USB_ATTACHED:
  1050. Log.e("-------->","------>USB_ATTACHED");
  1051. mWebView.loadUrl("javascript:printerCode('6')");
  1052. break;
  1053. }
  1054. }
  1055. };
  1056. private SerialPortManager serialPortManager;
  1057. private void toConnectLight(String name){
  1058. if (serialPortManager == null){
  1059. serialPortManager = new SerialPortManager();
  1060. serialPortManager.init(MainActivity.this, name, UserCache.getSerialRate(), new SerialPortManager.SerialCallBack() {
  1061. @Override
  1062. public void dataCallBack(String data) {
  1063. Log.e("--------->","------->data="+data);
  1064. }
  1065. @Override
  1066. public void openCallBack(int code) {
  1067. Log.e("--------->","------->openCallBack code="+code);
  1068. runOnUiThread(new Runnable() {
  1069. @Override
  1070. public void run() {
  1071. mWebView.loadUrl("javascript:responseLightCode('"+code+"')");
  1072. if (code == 1){
  1073. }else {
  1074. Toast.makeText(MainActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
  1075. }
  1076. }
  1077. });
  1078. }
  1079. @Override
  1080. public void closeCallBack(int code) {
  1081. }
  1082. });
  1083. }else {
  1084. serialPortManager.open();
  1085. }
  1086. }
  1087. @Override
  1088. protected void onDestroy() {
  1089. super.onDestroy();
  1090. if (cameraProvider!=null){
  1091. cameraProvider.unbindAll();
  1092. }
  1093. if (fixedThreadPool!=null){
  1094. fixedThreadPool.shutdown();
  1095. }
  1096. }
  1097. }