12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196 |
- package com.naz.sdkdemo;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothGatt;
- import android.bluetooth.BluetoothGattCharacteristic;
- import android.bluetooth.BluetoothGattService;
- import android.content.ContentValues;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.location.LocationManager;
- import android.os.Build;
- import android.os.Environment;
- import android.provider.MediaStore;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.View;
- import android.webkit.JavascriptInterface;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import android.widget.Toast;
- import com.clj.fastble.BleManager;
- import com.clj.fastble.callback.BleGattCallback;
- import com.clj.fastble.callback.BleNotifyCallback;
- import com.clj.fastble.callback.BleScanCallback;
- import com.clj.fastble.data.BleDevice;
- import com.clj.fastble.exception.BleException;
- import com.clj.fastble.scan.BleScanRuleConfig;
- import com.clj.fastble.utils.HexUtil;
- import com.google.common.util.concurrent.ListenableFuture;
- import com.google.gson.Gson;
- import com.google.gson.reflect.TypeToken;
- import com.naz.sdkdemo.activity.ble.comm.ObserverManager;
- import com.naz.sdkdemo.base.BaseActivity;
- import com.naz.sdkdemo.bean.PrintModule;
- import com.naz.sdkdemo.bean.PrintModule2;
- import com.naz.sdkdemo.bean.PrintModule3;
- import com.naz.sdkdemo.helper.SerialPortManager;
- import com.naz.sdkdemo.http.ApiHelper;
- import com.naz.sdkdemo.utils.MyTools;
- import com.naz.sdkdemo.weight.UserCache;
- import com.tencent.smtt.export.external.interfaces.WebResourceError;
- import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
- import com.tencent.smtt.sdk.WebSettings;
- import com.tencent.smtt.sdk.WebView;
- import com.tencent.smtt.sdk.WebViewClient;
- import net.posprinter.IConnectListener;
- import net.posprinter.IDeviceConnection;
- import net.posprinter.POSConnect;
- import net.posprinter.TSPLConst;
- import net.posprinter.TSPLPrinter;
- import java.io.File;
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Method;
- import java.lang.reflect.Type;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import androidx.annotation.NonNull;
- import androidx.camera.core.CameraSelector;
- import androidx.camera.core.ImageCapture;
- import androidx.camera.core.ImageCaptureException;
- import androidx.camera.core.Preview;
- import androidx.camera.lifecycle.ProcessCameraProvider;
- import androidx.core.app.ActivityCompat;
- import androidx.core.content.ContextCompat;
- import androidx.lifecycle.LifecycleOwner;
- import static net.posprinter.TSPLConst.FNT_SIMPLIFIED_CHINESE;
- import static net.posprinter.TSPLConst.ROTATION_90;
- public class MainActivity extends BaseActivity {
- private final String TAG = "HomeActivity";
- private WebView mWebView;
- private LinearLayout ll_nonet;
- private LinearLayout ll_web;
- private Button printBtn;
- private Button connectBtn;
- private Button connectLight;
- private Button turnOnLight;
- private Button closeLight;
- private TSPLPrinter printer;
- String savePath;
- private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
- private ProcessCameraProvider cameraProvider;
- private ImageCapture imageCapture;
- private String bleName;
- private int code=0;//0默认值,1未搜索到设备,2连接失败,3连接成功,4断开了,5打开通知失败,6打开通知成功
- @Override
- protected int getLayoutResId() {
- return R.layout.activity_home_web;
- }
- @Override
- protected void initView() {
- ll_nonet = findViewById(R.id.ll_nonet);
- ll_web = findViewById(R.id.ll_web);
- mWebView = findViewById(R.id.webview);
- checkNet();
- findViewById(R.id.bt_ref).setOnClickListener(new View.OnClickListener(){
- @Override
- public void onClick(View v) {
- getUrl();
- }
- });
- getUrl();
- WebSettings ws = mWebView.getSettings();
- // 网页内容的宽度是否可大于WebView控件的宽度
- ws.setLoadWithOverviewMode(false);
- // 保存表单数据
- ws.setSaveFormData(true);
- // 是否应该支持使用其屏幕缩放控件和手势缩放
- ws.setSupportZoom(true);
- ws.setBuiltInZoomControls(true);
- ws.setDisplayZoomControls(false);
- // 启动应用缓存
- ws.setAppCacheEnabled(true);
- // 设置缓存模式
- ws.setCacheMode(WebSettings.LOAD_DEFAULT);
- // setDefaultZoom api19被弃用
- // 设置此属性,可任意比例缩放。
- ws.setUseWideViewPort(true);
- // 不缩放
- mWebView.setInitialScale(100);
- mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
- // 告诉WebView启用JavaScript执行。默认的是false。
- ws.setJavaScriptEnabled(true);
- // 页面加载好以后,再放开图片
- ws.setBlockNetworkImage(false);
- // 使用localStorage则必须打开
- ws.setDomStorageEnabled(true);
- // WebView是否新窗口打开(加了后可能打不开网页)
- ws.setSupportMultipleWindows(true);
- // String systemUserAgent = MyTools.getUserAgent(ws, getApplicationContext());
- // ws.setUserAgentString(systemUserAgent + "Zuyu_Android");
- ws.setAllowContentAccess(true);
- ws.setJavaScriptCanOpenWindowsAutomatically(true);
- ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
- /** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用) */
- ws.setTextZoom(100);
- aIn = new AndroidInterface();
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- // 允许javascript出错
- try {
- Method method = Class.forName("android.webkit.WebView").
- getMethod("setWebContentsDebuggingEnabled", Boolean.TYPE);
- if (method != null) {
- method.setAccessible(true);
- method.invoke(null, true);
- }
- } catch (Exception e) {
- // do nothing
- }
- }
- mWebView.addJavascriptInterface(aIn, "androidJs");
- mWebView.setWebViewClient(new WebViewClient(){
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- ll_nonet.setVisibility(View.GONE);
- ll_web.setVisibility(View.VISIBLE);
- }
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
- if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) { // 4.0以上必须要加
- view.loadUrl(mUrl);
- return true;
- }
- return false;
- }
- @Override
- public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
- super.onReceivedError(view, request, error);
- Log.e("----------->","------->request="+request);
- Log.e("----------->","------->error="+error);
- }
- });
- printBtn = findViewById(R.id.print);
- printBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 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\"}]";
- // Gson gson=new Gson();
- // Type type = new TypeToken<List<PrintModule3>>(){}.getType();
- // List<PrintModule3> data = gson.fromJson(json, type);
- // if (data == null) {
- // return;
- // }
- // startPrint3(data);
- String json = "[{\n" +
- "\t\"now_date\": \"2024-04-14\",\n" +
- "\t\"box_date\": \"2024-03-27T08:55:01.569Z\",\n" +
- "\t\"delivery_flag\": 0,\n" +
- "\t\"status_dk_show\": \"已包\",\n" +
- "\t\"status_dk\": \"PACKAGED\",\n" +
- "\t\"print_flag\": 0,\n" +
- "\t\"no\": \"BZ2024032700001\",\n" +
- "\t\"device_code_show\": \"测试设备\",\n" +
- "\t\"device_code\": \"DV00001\",\n" +
- "\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
- "\t\"id\": \"560748673403850752\",\n" +
- "\t\"main_table_id\": null,\n" +
- "\t\"request_id\": null,\n" +
- "\t\"box_order_product\": {\n" +
- "\t\t\"customer_no\": \"C00912\",\n" +
- "\t\t\"process_title_two\": null,\n" +
- "\t\t\"customer_name\": \"信息中心客户-测试\",\n" +
- "\t\t\"color_two\": null,\n" +
- "\t\t\"dealer_name\": \"信息中心经销商-测试\",\n" +
- "\t\t\"order_item_id\": \"553451940644175872\",\n" +
- "\t\t\"process_title\": \"同步\",\n" +
- "\t\t\"material_title\": \"大王椰1800尊贵型E0指接香杉木-银盾抗菌生态免漆板W\",\n" +
- "\t\t\"order_no\": \"SO202403070001\",\n" +
- "\t\t\"box_num\": 50,\n" +
- "\t\t\"dealer_no\": \"C00911\",\n" +
- "\t\t\"color\": \"春华秋实\",\n" +
- "\t\t\"material_no\": \"BC170202000001\",\n" +
- "\t\t\"material_size\": \"3300-4\",\n" +
- "\t\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
- "\t\t\"id\": \"560748673416433664\",\n" +
- "\t\t\"main_table_id\": \"560748673403850752\",\n" +
- "\t\t\"request_id\": null\n" +
- "\t},\n" +
- "\t\"is_choose\": true\n" +
- "}]";
- Gson gson=new Gson();
- Type type = new TypeToken<List<PrintModule2>>(){}.getType();
- List<PrintModule2> data = gson.fromJson(json, type);
- if (data == null) {
- return;
- }
- startPrint2(data);
- }
- });
- connectBtn = findViewById(R.id.connect);
- connectBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- connectUSB(searchUsb());
- }
- });
- connectLight = findViewById(R.id.connect2);
- turnOnLight = findViewById(R.id.light);
- connectLight.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- toConnectLight(UserCache.getSerialName());
- }
- });
- turnOnLight.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (serialPortManager != null){
- serialPortManager.turnOnLight(6);
- }
- }
- });
- closeLight = findViewById(R.id.closeLight);
- closeLight.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (serialPortManager!=null){
- serialPortManager.close();
- serialPortManager = null;
- }
- }
- });
- findViewById(R.id.take_photo).setOnClickListener(new View.OnClickListener(){
- @Override
- public void onClick(View v) {
- Log.e("-------->","------->path="+getImagePath("123.jpg"));
- savePicture(new File(getImagePath("123.jpg")), "ceshi", "202119");
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // savePicture(new File(getImagePath("234.jpg")), "ceshi", "202119");
- // }
- // }, 20000);
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // savePicture(new File(getImagePath("345.jpg")), "ceshi", "202119");
- // }
- // }, 30000);
- // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
- }
- });
- findViewById(R.id.start_scan).setOnClickListener(new View.OnClickListener(){
- @Override
- public void onClick(View v) {
- checkPermissions("dawangye");
- // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
- }
- });
- findViewById(R.id.close_scan).setOnClickListener(new View.OnClickListener(){
- @Override
- public void onClick(View v) {
- closeScan();
- // startActivity(new Intent(MainActivity.this, CaremaActivity.class));
- }
- });
- Log.e("------->","-------->"+UserCache.getSerialName());
- }
- private AndroidInterface aIn;
- private class AndroidInterface {
- @JavascriptInterface
- public void takePhoto(String path, String name) {
- Log.e(TAG, "takePhoto");
- toTakePhoto(path, name);
- }
- @JavascriptInterface
- public void refreshData() {
- Log.e(TAG, "clearCache");
- mWebView.clearCache(false);
- mWebView.reload();
- }
- //打印
- @JavascriptInterface
- public void printF(String json) {
- Log.e(TAG, "printF json"+json);
- Gson gson=new Gson();
- Type type = new TypeToken<List<PrintModule>>(){}.getType();
- List<PrintModule> data = gson.fromJson(json, type);
- if (data == null) {
- return;
- }
- startPrint(data);
- }
- @JavascriptInterface
- public void printF2(String json) {
- Log.e(TAG, "printF2 json"+json);
- Gson gson=new Gson();
- Type type = new TypeToken<List<PrintModule2>>(){}.getType();
- List<PrintModule2> data = gson.fromJson(json, type);
- if (data == null) {
- return;
- }
- startPrint2(data);
- }
- @JavascriptInterface
- public void printF3(String json) {
- Log.e(TAG, "printF3 json"+json);
- Gson gson=new Gson();
- Type type = new TypeToken<List<PrintModule3>>(){}.getType();
- List<PrintModule3> data = gson.fromJson(json, type);
- if (data == null) {
- return;
- }
- startPrint3(data);
- }
- @JavascriptInterface
- public void startScan(String name) {
- Log.e(TAG, "startScan name"+name);
- checkPermissions(name);
- }
- @JavascriptInterface
- public void closeScan() {
- Log.e(TAG, "closeScan");
- closeScan();
- }
- @JavascriptInterface
- public void openCamera() {
- Log.e(TAG, "openCamera");
- toOpenCamera();
- }
- @JavascriptInterface
- public void closeCamera() {
- Log.e(TAG, "closeCamera");
- toCloseCamera();
- }
- @JavascriptInterface
- public void openPrinter() {
- Log.e(TAG, "openPrinter");
- connectUSB(searchUsb());
- }
- @JavascriptInterface
- public void closePrinter() {
- Log.e(TAG, "closePrinter");
- closeUSB();
- }
- @JavascriptInterface
- public void connectLight(String name) {
- Log.e(TAG, "connectLight");
- toConnectLight(name);
- }
- @JavascriptInterface
- public void controlLight(int address, int type) {
- Log.e(TAG, "openLight"+"address="+address+",type="+type);
- if (serialPortManager != null){
- serialPortManager.turnOnLight(address, type);
- }
- }
- @JavascriptInterface
- public void disConnectLight() {
- Log.e(TAG, "closeLight");
- if (serialPortManager!=null){
- serialPortManager.close();
- serialPortManager = null;
- }
- }
- @JavascriptInterface
- public void getPort() {
- Log.e(TAG, "getPort");
- mWebView.loadUrl("javascript:getPort('" + UserCache.getSerialPortName() + "')");
- }
- }
- private void toCloseCamera() {
- if (cameraProvider!=null){
- cameraProvider.unbindAll();
- }
- }
- private void toOpenCamera() {
- // 请求 CameraProvider
- cameraProviderFuture = ProcessCameraProvider.getInstance(this);
- //检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
- cameraProviderFuture.addListener(() -> {
- try {
- ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
- bindPreview(cameraProvider);
- } catch (ExecutionException | InterruptedException e) {
- // No errors need to be handled for this Future.
- // This should never be reached.
- }
- }, ContextCompat.getMainExecutor(this));
- }
- private void toTakePhoto(String path, String name) {
- Log.e("-------->","------>toTakePhoto");
- long timeStamp = System.currentTimeMillis();
- savePath = timeStamp+".jpg";
- // 通过 ContentValues 对象设置文件名和文件类型
- ContentValues contentValues = new ContentValues();
- contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, savePath);
- contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
- File dir = new File(Environment.getExternalStorageDirectory() + "/camera/");
- if (!dir.exists()) {
- dir.mkdirs();
- }
- //创建文件
- File file = new File(dir,savePath);
- ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
- imageCapture.takePicture(
- // 第一个参数 OutputFileOptions 指定了照片保存的位置和格式等信息。
- outputFileOptions,
- // 第二个参数 Executor 指定了保存照片时要运行的线程。
- ContextCompat.getMainExecutor(this),
- // 第三个参数 OnImageSavedCallback 指定了保存照片完成后的回调函数,可以在其中进行一些提示或其他操作。
- new ImageCapture.OnImageSavedCallback() {
- @SuppressLint("RestrictedApi")
- @Override
- public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
- Log.e("-------->","------>savePath="+outputFileResults.getSavedUri().getPath());
- Log.e("-------->","------>保存成功");
- // Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
- savePicture(file, path, name);
- mWebView.loadUrl("javascript:uploadPhotoPath('" + outputFileOptions.getFile().getAbsolutePath() + "')");
- }
- @Override
- public void onError(@NonNull ImageCaptureException exception) {
- Log.e("----------->","------->"+exception.getMessage());
- // Toast.makeText(MainActivity.this, "Error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
- }
- });
- }
- boolean isStart = false;
- ExecutorService fixedThreadPool;
- private void savePicture(File file, String path, String name) {
- if (!isStart){
- isStart = true;
- int numberOfCores = Runtime.getRuntime().availableProcessors();
- Log.i("--------->", "-------->cpu核心数" + numberOfCores);
- fixedThreadPool = Executors.newFixedThreadPool(2*numberOfCores+1);
- }
- try {
- fixedThreadPool.execute(new Runnable() {
- @Override
- public void run() {
- Log.i("--------->", "-------->uploadPicture" + file.getAbsolutePath());
- ApiHelper.uploadPicture(MainActivity.this, file, path, name);
- }
- });
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- private void checkNet() {
- if (!MyTools.isNetworkAvailable(getApplicationContext())) {
- ll_nonet.setVisibility(View.VISIBLE);
- ll_web.setVisibility(View.GONE);
- } else {
- ll_nonet.setVisibility(View.GONE);
- ll_web.setVisibility(View.VISIBLE);
- }
- }
- String mUrl = "https://dwytb.qingyaokeji.com/index.html#/";
- private void getUrl() {
- mWebView.loadUrl(mUrl);
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
- mWebView.goBack();
- return true;
- }
- return super.onKeyDown(keyCode, event);
- }
- static int mPot = 8;//mm转像素8倍
- static int mWFont = 24;//字体宽度
- static int mHFont = 24;//字体高度
- static int mPaperWidth = 78;//纸张宽度78mm
- static int mPaperHeight = 132;//纸张高度132mm
- static int fontSizeMultiple = 2;//字体倍数
- static int mOffsetY = 5;//打印开始点离左边的距离(Y轴),5mm
- static int mOffsetX = mPaperWidth-5;//打印开始点离上边的距离(X轴),5mm
- static int mFontWidth = mWFont * fontSizeMultiple;//文字的宽度
- static int mFontHeight = mHFont * fontSizeMultiple;//文字的高度
- static int mSpace = 4;//行列间隔-----5mm
- static int mTextSpace = 1;//换行间距----2mm
- static int mCodeSize = 30;//二维码宽高----30mm
- private void startPrint(List<PrintModule> data) {
- for (PrintModule module:data) {
- printer.sizeMm(mPaperWidth, mPaperHeight)
- .density(10)
- .reference(mPaperWidth*mPot, 0)
- .direction(TSPLConst.DIRECTION_FORWARD)
- .cls()
- .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号:")
- .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.no)
- .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称:");
- String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
- printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
- int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
- if (!TextUtils.isEmpty(productName[1])){
- currentHeight = currentHeight-mTextSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
- currentHeight = currentHeight-mFontHeight;
- }
- if (!TextUtils.isEmpty(productName[2])){
- currentHeight = currentHeight-mTextSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
- currentHeight = currentHeight-mFontHeight;
- }
- currentHeight = currentHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商:")
- .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.customer_name);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号:")
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_no)
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量:")
- .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_num);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色:")
- .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.decor_code_show);
- if (module.decor_two_code_show!=null){
- 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);
- }
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺:")
- .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.craft_type_code_show);
- if (module.craft_type_two_code_show!=null){
- 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);
- }
- printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
- printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.box_no);
- printer.print();
- }
- }
- private void startPrint2(List<PrintModule2> data) {
- for (PrintModule2 module:data) {
- printer.sizeMm(mPaperWidth, mPaperHeight)
- .density(10)
- .reference(mPaperWidth*mPot, 0)
- .direction(TSPLConst.DIRECTION_FORWARD)
- .cls()
- .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号:")
- .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.order_no)
- .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称:");
- String[] productName = getStrs(module.box_order_product.material_title, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
- printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
- int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
- if (!TextUtils.isEmpty(productName[1])){
- currentHeight = currentHeight-mTextSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
- currentHeight = currentHeight-mFontHeight;
- }
- if (!TextUtils.isEmpty(productName[2])){
- currentHeight = currentHeight-mTextSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
- currentHeight = currentHeight-mFontHeight;
- }
- currentHeight = currentHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商:")
- .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.customer_name);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号:")
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.no)
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量:")
- .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.box_num);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色:")
- .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.color);
- if (module.box_order_product.color_two!=null){
- 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);
- }
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺:")
- .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.process_title);
- if (module.box_order_product.process_title_two!=null){
- 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);
- }
- printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
- printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.no);
- printer.print();
- }
- }
- private void startPrint3(List<PrintModule3> data) {
- for (PrintModule3 module:data) {
- printer.sizeMm(mPaperWidth, mPaperHeight)
- .density(10)
- .reference(mPaperWidth*mPot, 0)
- .direction(TSPLConst.DIRECTION_FORWARD)
- .cls()
- .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_code_show);
- String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot);
- printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
- int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
- if (!TextUtils.isEmpty(productName[1])){
- currentHeight = currentHeight-mTextSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
- }
- if (!TextUtils.isEmpty(productName[2])){
- currentHeight = currentHeight-mTextSpace*mPot-mFontHeight;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
- }
- currentHeight = currentHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "商标编码:")
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.material_code);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "余标:")
- .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.qty);
- printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.roll_qr_code), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.roll_qr_code);
- currentHeight = currentHeight-mFontHeight-mSpace*mPot;
- printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
- 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);
- printer.print();
- }
- }
- //选择相机并绑定生命周期和用例
- private void bindPreview(@NonNull ProcessCameraProvider cp) {
- this.cameraProvider=cp;
- Preview preview = new Preview.Builder()
- .build();
- @SuppressLint("UnsafeOptInUsageError")
- CameraSelector cameraSelector = new CameraSelector.Builder()
- .requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
- .build();
- // 创建一个 ImageCapture 对象,用于拍摄照片。
- // 设置拍照模式为最小化延迟模式,这意味着拍照时将尽可能快地捕获图像。
- imageCapture = new ImageCapture.Builder()
- .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
- // 设置JPEG的质量为85%
- .setJpegQuality(85)
- .build();
- cameraProvider.unbindAll();//解绑组件
- cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
- // preview.setSurfaceProvider(previewView.getSurfaceProvider());
- }
- public static int getStrLength(String xm){
- int xmLength = 0;
- for (int i = 0; i < xm.length(); i++) {
- char chr = xm.charAt(i);
- if (isChinese(chr)){
- xmLength+=(mWFont*fontSizeMultiple);
- }else {
- xmLength+=(mWFont*fontSizeMultiple/2);
- }
- }
- Log.e("------->","----->xmStrLength="+xmLength);
- return xmLength;
- }
- public static String[] getStrs(String xm, int maxLength){
- Log.e("------->","----->maxLength="+maxLength);
- String[] resultStrs = new String[3];
- int xmLength = 0;
- int xmIndex = 0;
- String xmStr1 = "", xmStr2 = "", xmStr3 = "";
- boolean isLn = false;
- for (int i = 0; i < xm.length(); i++) {
- char chr = xm.charAt(i);
- if (isChinese(chr)){
- xmLength+=(mWFont*fontSizeMultiple);
- }else {
- xmLength+=(mWFont*fontSizeMultiple/2);
- }
- if (!isLn){
- if (xmLength>maxLength){
- isLn = true;
- xmIndex = i;
- }
- }
- }
- Log.e("------->","----->index="+xmIndex);
- String str = xm;
- if (xmLength>maxLength){
- xmStr1 = str.substring(0, xmIndex);
- String xmStr = xm.substring(xmIndex);
- int xmLength2 = 0;
- int xmIndex2 = 0;
- boolean isLn2 = false;
- for (int i = 0; i < xmStr.length(); i++) {
- char chr = xmStr.charAt(i);
- if (isChinese(chr)){
- xmLength2+=24*fontSizeMultiple;
- }else {
- xmLength2+=12*fontSizeMultiple;
- }
- if (!isLn2){
- String str2 = xmStr;
- if (xmLength2>maxLength){
- isLn2 = true;
- xmIndex2 = i;
- xmStr2 = str2.substring(0, xmIndex2);
- xmStr3 = xmStr.substring(xmIndex2);
- }else{
- xmStr2 = str2;
- xmStr3 = "";
- }
- }
- }
- }else {
- xmStr1 = str;
- xmStr2 = "";
- xmStr3 = "";
- }
- Log.e("------->","----->xmStr1="+xmStr1);
- Log.e("------->","----->xmStr2="+xmStr2);
- Log.e("------->","----->xmStr3="+xmStr3);
- resultStrs[0] = xmStr1;
- resultStrs[1] = xmStr2;
- resultStrs[2] = xmStr3;
- return resultStrs;
- }
- public static boolean isChinese(char chr) {
- boolean isChinese = false;
- //if ((int)str[i] > 127)//判断是否是汉字
- if ((int)chr > 0x4E00 && (int)chr < 0x9FA5) {
- isChinese = true;
- } else {
- isChinese = false; ;
- }
- return isChinese;
- }
- public static String getImagePath(String imageName) {
- File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
- File imageFile = new File(picturesDir, imageName);
- return imageFile.exists() ? imageFile.getAbsolutePath() :"";
- }
- private static final int REQUEST_CODE_OPEN_GPS = 1;
- private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
- private void checkPermissions(String name) {
- bleName = name;
- BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (!bluetoothAdapter.isEnabled()) {
- Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
- return;
- }
- String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
- List<String> permissionDeniedList = new ArrayList<>();
- for (String permission : permissions) {
- int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
- if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
- onPermissionGranted(permission);
- } else {
- permissionDeniedList.add(permission);
- }
- }
- if (!permissionDeniedList.isEmpty()) {
- Log.e("------->","----->checkPermissions permissionDeniedList="+permissionDeniedList);
- String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
- ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
- }
- }
- private void onPermissionGranted(String permission) {
- Log.e("------->","----->onPermissionGranted permission="+permission);
- switch (permission) {
- case Manifest.permission.ACCESS_FINE_LOCATION:
- setScanRule();
- startScan(bleName);
- // Log.e("------->","----->checkGPSIsOpen="+checkGPSIsOpen());
- // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
- // new AlertDialog.Builder(this)
- // .setTitle(R.string.notifyTitle)
- // .setMessage(R.string.gpsNotifyMsg)
- // .setNegativeButton(R.string.cancel,
- // new DialogInterface.OnClickListener() {
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // finish();
- // }
- // })
- // .setPositiveButton(R.string.setting,
- // new DialogInterface.OnClickListener() {
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- // startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
- // }
- // })
- //
- // .setCancelable(false)
- // .show();
- // } else {
- // setScanRule();
- // startScan(bleName);
- // }
- break;
- }
- }
- //关闭蓝牙扫码器
- BleDevice mBleDevice;
- BluetoothGattCharacteristic mCharacteristic;
- private void closeScan(){
- if (mBleDevice!=null){
- if (BleManager.getInstance().isConnected(mBleDevice)) {
- BleManager.getInstance().disconnect(mBleDevice);
- }
- BleManager.getInstance().removeNotifyCallback(mBleDevice, mCharacteristic.getService().getUuid().toString());
- BleManager.getInstance().clearCharacterCallback(mBleDevice);
- BleManager.getInstance().removeConnectGattCallback(mBleDevice);
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == REQUEST_CODE_OPEN_GPS) {
- // if (checkGPSIsOpen()) {
- setScanRule();
- startScan(bleName);
- // }
- }
- }
- private boolean checkGPSIsOpen() {
- // LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
- // if (locationManager == null)
- // return false;
- // return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
- boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
- return isGpsEnabled || isNetworkEnabled;
- }
- private void setScanRule() {
- BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
- .setScanTimeOut(10000) // 扫描超时时间,可选,默认10秒
- .build();
- BleManager.getInstance().initScanRule(scanRuleConfig);
- }
- //开始蓝牙扫码器
- private void startScan(String name) {
- // Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
- BleManager.getInstance().scan(new BleScanCallback() {
- @Override
- public void onScanStarted(boolean success) {
- }
- @Override
- public void onLeScan(BleDevice bleDevice) {
- super.onLeScan(bleDevice);
- }
- @Override
- public void onScanning(BleDevice bleDevice) {
- if ((name+"BLE").equals(bleDevice.getName())){
- // Toast.makeText(MainActivity.this, "名字匹配去链接", Toast.LENGTH_SHORT).show();
- if (!BleManager.getInstance().isConnected(bleDevice)) {
- BleManager.getInstance().cancelScan();
- connect(bleDevice);
- }
- }else {
- // Toast.makeText(MainActivity.this, "名字不匹配", Toast.LENGTH_SHORT).show();
- }
- }
- @Override
- public void onScanFinished(List<BleDevice> scanResultList) {
- boolean isScanSuccess = false;
- for (int i = 0; i < scanResultList.size(); i++) {
- BleDevice bleDevice = scanResultList.get(i);
- if ((name+"BLE").equals(bleDevice.getName())){
- isScanSuccess = true;
- }
- }
- // Toast.makeText(MainActivity.this, "扫描完成,是否成功="+isScanSuccess, Toast.LENGTH_SHORT).show();
- if (isScanSuccess){
- mWebView.loadUrl("javascript:responseCode('1')");
- }
- }
- });
- }
- private void connect(final BleDevice bleDevice) {
- BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
- @Override
- public void onStartConnect() {
- }
- @Override
- public void onConnectFail(BleDevice bleDevice, BleException exception) {
- Log.e("-------->","------>连接失败");
- // Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
- mWebView.loadUrl("javascript:responseCode('2')");
- }
- @Override
- public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
- Log.e("-------->","------>连接成功");
- // Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
- mBleDevice = bleDevice;
- mWebView.loadUrl("javascript:responseCode('3')");
- if (BleManager.getInstance().isConnected(bleDevice)) {
- BluetoothGattService bluetoothGattService = null;
- for (BluetoothGattService service : gatt.getServices()) {
- if (service.getUuid().toString().contains("0000feea")){
- bluetoothGattService = service;
- }
- }
- if (bluetoothGattService!=null){
- List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
- for (int i = 0; i < characteristics.size(); i++) {
- BluetoothGattCharacteristic characteristic = characteristics.get(i);
- if (characteristic.getUuid().toString().contains("00002aa1")){
- mCharacteristic = characteristic;
- BleManager.getInstance().notify(
- bleDevice,
- characteristic.getService().getUuid().toString(),
- characteristic.getUuid().toString(),
- new BleNotifyCallback() {
- @Override
- public void onNotifySuccess() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Toast.makeText(MainActivity.this, "打开通知成功", Toast.LENGTH_SHORT).show();
- Log.e("-------->","-------->打开通知成功");
- mWebView.loadUrl("javascript:responseCode('6')");
- }
- });
- }
- @Override
- public void onNotifyFailure(final BleException exception) {
- Log.e("-------->","------>打开通知失败");
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Toast.makeText(MainActivity.this, "连接通知失败", Toast.LENGTH_SHORT).show();
- mWebView.loadUrl("javascript:responseCode('5')");
- }
- });
- }
- @Override
- public void onCharacteristicChanged(byte[] data) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Log.e("-------->","-------->data="+(HexUtil.formatHexString(data, true)));
- Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(data, false))));
- // Toast.makeText(MainActivity.this, "接收数据="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))), Toast.LENGTH_SHORT).show();
- mWebView.loadUrl("javascript:responseData('"+(hexStringToGbk(HexUtil.formatHexString(data, false)))+"')");
- // Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))));
- // Log.e("-------->","-------->data="+(HexUtil.formatHexString(characteristic.getValue(), true)));
- }
- });
- }
- });
- }
- }
- }
- }
- }
- @Override
- public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
- mBleDevice = null;
- if (isActiveDisConnected) {
- Log.e("-------->","------>断开了");
- mWebView.loadUrl("javascript:responseCode('4')");
- } else {
- Log.e("-------->","------>连接断开");
- mWebView.loadUrl("javascript:responseCode('5')");
- ObserverManager.getInstance().notifyObserver(bleDevice);
- }
- }
- });
- }
- public String hexStringToGbk(String hexString) {
- byte[] bytes = new byte[hexString.length() / 2];
- for (int i = 0; i < hexString.length(); i += 2) {
- bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
- + Character.digit(hexString.charAt(i+1), 16));
- }
- try {
- return new String(bytes, "GBK");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- return null;
- }
- }
- IDeviceConnection curConnect = null;
- private void connectUSB(String pathName){
- if (curConnect!=null){
- curConnect.close();
- }
- curConnect = POSConnect.createDevice(POSConnect.DEVICE_TYPE_USB);
- curConnect.connect(pathName, connectListener);
- printer = new TSPLPrinter(curConnect);
- }
- public String searchUsb() {
- List<String> usbNames = POSConnect.getUsbDevices(this);
- // XToast.showToast("usbNames="+usbNames.size());
- String ret = "";
- if (usbNames.size()>0) {
- ret = usbNames.get(0);
- }
- Log.e("-------->","------>ret="+ret);
- return ret;
- }
- private void closeUSB() {
- if (curConnect!=null){
- curConnect.close();
- }
- }
- private IConnectListener connectListener = new IConnectListener() {
- @Override
- public void onStatus(int code, String connInfo, String msg) {
- switch (code){
- case POSConnect.CONNECT_SUCCESS:
- Log.e("-------->","------>CONNECT_SUCCESS");
- mWebView.loadUrl("javascript:printerCode('1')");
- break;
- case POSConnect.CONNECT_FAIL:
- Log.e("-------->","------>CONNECT_FAIL");
- mWebView.loadUrl("javascript:printerCode('2')");
- break;
- case POSConnect.CONNECT_INTERRUPT:
- Log.e("-------->","------>CONNECT_INTERRUPT");
- mWebView.loadUrl("javascript:printerCode('3')");
- break;
- case POSConnect.SEND_FAIL:
- Log.e("-------->","------>SEND_FAIL");
- mWebView.loadUrl("javascript:printerCode('4')");
- break;
- case POSConnect.USB_DETACHED:
- Log.e("-------->","------>USB_DETACHED");
- mWebView.loadUrl("javascript:printerCode('5')");
- break;
- case POSConnect.USB_ATTACHED:
- Log.e("-------->","------>USB_ATTACHED");
- mWebView.loadUrl("javascript:printerCode('6')");
- break;
- }
- }
- };
- private SerialPortManager serialPortManager;
- private void toConnectLight(String name){
- if (serialPortManager == null){
- serialPortManager = new SerialPortManager();
- serialPortManager.init(MainActivity.this, name, UserCache.getSerialRate(), new SerialPortManager.SerialCallBack() {
- @Override
- public void dataCallBack(String data) {
- Log.e("--------->","------->data="+data);
- }
- @Override
- public void openCallBack(int code) {
- Log.e("--------->","------->openCallBack code="+code);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mWebView.loadUrl("javascript:responseLightCode('"+code+"')");
- if (code == 1){
- }else {
- Toast.makeText(MainActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- @Override
- public void closeCallBack(int code) {
- }
- });
- }else {
- serialPortManager.open();
- }
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- if (cameraProvider!=null){
- cameraProvider.unbindAll();
- }
- if (fixedThreadPool!=null){
- fixedThreadPool.shutdown();
- }
- }
- }
|