MainActivity.java 49 KB

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