wjc
2025-01-13 3c18f8e5f2d54c6cb2e4d2e0e5fc538a6a2ea188
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package com.hdl.photovoltaic.ui.device;
 
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
 
 
import androidx.appcompat.content.res.AppCompatResources;
 
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.hdl.photovoltaic.R;
import com.hdl.photovoltaic.base.CustomBaseActivity;
import com.hdl.photovoltaic.config.UserConfigManage;
import com.hdl.photovoltaic.other.HdlCommonLogic;
import com.hdl.photovoltaic.uni.HDLUniMP;
import com.hdl.photovoltaic.utils.LocalManageUtil;
import com.hdl.photovoltaic.utils.PermissionUtils;
import com.jaeger.library.StatusBarUtil;
import com.zxing.IZxingActivity;
import com.zxing.camera.CameraManager;
import com.zxing.decode.DecodeThread;
import com.zxing.decode.RGBLuminanceSource;
import com.zxing.utils.BeepManager;
import com.zxing.utils.CaptureActivityHandler;
import com.zxing.utils.InactivityTimer;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Hashtable;
import java.util.Locale;
 
/**
 * 扫一扫
 */
public class ScanActivity extends Activity implements IZxingActivity, SurfaceHolder.Callback {
    private static final String TAG = ScanActivity.class.getSimpleName();
    private final int REQUEST_CODE = 33;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private TextView tvCancel;
    private Rect mCropRect = null;
    private boolean isHasSurface = false;
 
 
    @Override
    public Handler getHandler() {
        return handler;
    }
 
    @Override
    public void drawViewfinder() {
 
    }
 
    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }
 
    public int getRootLayoutId() {
        return R.layout.activity_scan;
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Resources resources = this.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale locale = LocalManageUtil.getLocale(UserConfigManage.getInstance().getCurrentAppLanguage());
        // app locale 默认简体中文
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);
 
        StatusBarUtil.setTranslucentForImageViewInFragment(this,
                0, null);
        StatusBarUtil.setLightMode(this);
 
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //设置根视图
        View mContentView = LayoutInflater.from(this).inflate(getRootLayoutId(), null);
        setContentView(mContentView);
 
        afterViewBind(mContentView, savedInstanceState);
 
 
    }
 
    public void afterViewBind(View rootView, Bundle savedInstanceState) {
        tvCancel = findViewById(R.id.tv_text_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                enterGallery();
            }
        });
        scanPreview = findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        ImageView scanLine = findViewById(R.id.capture_scan_line);
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
 
        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation
                .RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
                0.9f);
        animation.setDuration(2000);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);
        ImageView imageView = findViewById(R.id.light_iv);
        //开启闪光灯按钮事件
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                if (v.isSelected()) {
                    imageView.setImageDrawable(AppCompatResources.getDrawable(ScanActivity.this, com.zxing.R.drawable.fast_scan_light_open));
                } else {
                    imageView.setImageDrawable(AppCompatResources.getDrawable(ScanActivity.this, com.zxing.R.drawable.fast_scan_light_close));
                }
                flashLightOnOrOff();
 
            }
        });
    }
 
    public void enterGallery() {
        // 进入图库
        Intent pickIntent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//启动系统相册
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, REQUEST_CODE);
 
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        handler = null;
        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            scanPreview.getHolder().addCallback(this);
        }
 
        inactivityTimer.onResume();
    }
 
    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        if (cameraManager != null) {
            cameraManager.closeDriver();
        }
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }
 
    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }
 
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.d(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }
 
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }
 
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
 
    }
 
    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    @Override
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        doProcess(rawResult.getText());
        restartPreviewAfterDelay(3000);
    }
 
    private void initCamera(SurfaceHolder surfaceHolder) {
//        PermissionUtils.requestPermissionsResultCallback(this, Manifest.permission.CAMERA, new PermissionUtils.PermissionState() {
//            @Override
//            public void Success(int value) {
//                if (value == PermissionUtils.STATUS_REFUSE_PERMANENT | value == PermissionUtils.STATUS_REFUSE) {
////                            HdlThreadLogic.toast(_mActivity, R.string.permission_open);
//                    Toast.makeText(ScanActivity.this, R.string.capture_no_camera, Toast.LENGTH_SHORT).show();
//                    return;
//                }
 
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(ScanActivity.this, cameraManager, DecodeThread.ALL_MODE);
            }
            initCrop();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            Toast.makeText(ScanActivity.this, R.string.capture_no_camera, Toast.LENGTH_SHORT).show();
            finish();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
            Toast.makeText(ScanActivity.this, R.string.capture_no_camera, Toast.LENGTH_SHORT).show();
            finish();
        }
//            }
//        }, true);
    }
 
    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(com.zxing.R.id.restart_preview, delayMS);
        }
    }
 
    @Override
    public Rect getCropRect() {
        return mCropRect;
    }
 
    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;
 
        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);
 
        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();
 
        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();
 
        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();
 
        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;
 
        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;
 
        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }
 
    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
 
    private void doProcess(String result) {
        /*if (!DeviceHelper.getNetworkState()) {
            Toast.makeText(this, R.string.capture_no_network, Toast.LENGTH_SHORT).show();
            return;
        }*/
 
        if (TextUtils.isEmpty(result)) {
            Toast.makeText(this, R.string.capture_no_result, Toast.LENGTH_SHORT).show();
        } else {
            if (result.startsWith("https://") || result.startsWith("http://")) {
                Intent intent = new Intent();
                intent.putExtra("data", result);
                setResult(RESULT_OK, intent);
                finish();
                //EventBus事件分发
                HdlCommonLogic.getInstance().postEventBusSticky(
                        HDLUniMP.UNI_EVENT_REPLY_HOME_ADD,
                        HDLUniMP.UNI_EVENT_REPLY_HOME_ADD,
                        result);
            } else {
                Toast.makeText(this, R.string.not_delivery_qr_code, Toast.LENGTH_SHORT).show();
            }
 
        }
    }
 
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Uri originalUri = data.getData();
            if (originalUri != null) {
                String path = originalUri.getPath();
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(originalUri, proj, null, null, null);
                if (cursor != null) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    path = cursor.getString(column_index);
                    cursor.close();
                }
 
                if (!TextUtils.isEmpty(path)) {
                    handleQRCodeFormPhoto(path);
                } else {
//                    Toast.makeText(this, R.string.pic_error, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
 
    /**
     * 解析图库选择的二维码
     */
    public void handleQRCodeFormPhoto(final String filePath) {
        Thread dealThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Hashtable<DecodeHintType, String> hints = new Hashtable<>();
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                RGBLuminanceSource source = null;
                try {
                    source = new RGBLuminanceSource(filePath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
                QRCodeReader reader = new QRCodeReader();
                Result result;
                try {
                    result = reader.decode(binaryBitmap, hints);
                    if (!TextUtils.isEmpty(result.getText())) {
                        dealUIInfo(result.getText());
                    } else {
                        dealUIInfo(null);
                    }
                } catch (NotFoundException | ChecksumException | FormatException e) {
                    dealUIInfo(null);
                    e.printStackTrace();
                }
            }
        });
        dealThread.start();
    }
 
    private void dealUIInfo(final Object progressInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressInfo == null) {
                    Toast.makeText(ScanActivity.this, R.string.capture_no_result2, Toast.LENGTH_SHORT).show();
                } else {
                    doProcess(progressInfo.toString());
                }
            }
        });
    }
 
    /**
     * 闪光灯开启或者关闭
     */
    private void flashLightOnOrOff() {
//
        android.hardware.Camera camera = cameraManager.getCamera();
        if (camera == null) {
            return;
        }
        android.hardware.Camera.Parameters parameters = camera.getParameters();
//        判断闪光灯当前状态
        if (Camera.Parameters.FLASH_MODE_OFF.equals(parameters.getFlashMode())) {
            onLight(camera, parameters);
        } else if (Camera.Parameters.FLASH_MODE_TORCH.equals(parameters.getFlashMode())) {
            offLight(camera, parameters);
        }
    }
 
    private void onLight(android.hardware.Camera camera, Camera.Parameters parameters) {
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
    }
 
    private void offLight(android.hardware.Camera camera, Camera.Parameters parameters) {
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
    }
 
}