Android:扫码功能

 

1、引入

    implementation 'com.journeyapps:zxing-android-embedded:3.5.0'

2、使用:

public void initScan() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        // 设置要扫描的条码类型,ONE_D_CODE_TYPES:一维码,QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
        integrator.setPrompt(""); //底部的提示文字,设为""可以置空
        integrator.setCameraId(0); //前置或者后置摄像头
        integrator.setBeepEnabled(true); //扫描成功的「哔哔」声,默认开启
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == IntentIntegrator.REQUEST_CODE) {
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
            if (scanResult != null && scanResult.getContents() != null) {
                String result = scanResult.getContents();
                LogUtil.d("扫码返回: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.has(Constant.USERPOLICEMENID)) {
                       //TODO  逻辑
                     
                    } else {
                        ToastUtil.showShortToast("未扫描到有效的信息");
                    }
                } catch (Exception e) {
                    ToastUtil.showShortToast("未扫描到有效的信息");
                    e.printStackTrace();
                }
            } else {
                ToastUtil.showShortToast("未扫描到有效的信息");
            }
        }
    }

3、ScanActivity

public class ScanActivity extends BackActivity {

    @BindView(R.id.dbv)
    DecoratedBarcodeView mDbv;
    private CaptureManager captureManager;

    @Override
    protected int getLayoutId() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_scan;
    }

    @Override
    protected void init() {
        super.init();
        captureManager = new CaptureManager(this, mDbv);
        captureManager.initializeFromIntent(getIntent(), getSavedInstanceState());
        captureManager.decode();
    }

    @Override
    public void onSaveInstanceState(@NotNull Bundle outState, @NotNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mDbv.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

}

4、布局文件

activity_scan
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.main.alarmassistant.ScanActivity">


    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/dbv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:zxing_framing_rect_height="200dp"
        app:zxing_framing_rect_width="200dp"
        app:zxing_preview_scaling_strategy="fitXY"
        app:zxing_scanner_layout="@layout/view_qr"
        app:zxing_use_texture_view="true" />
</LinearLayout>
view_qr
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.journeyapps.barcodescanner.BarcodeView
        android:id="@+id/zxing_barcode_surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_framing_rect_height="50dp"
        app:zxing_framing_rect_width="250dp" />

    <com.x.x.widget.QrView
        android:id="@+id/zxing_viewfinder_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_possible_result_points="@color/color_white"
        app:zxing_result_view="@color/zxing_custom_result_view"
        app:zxing_viewfinder_laser="@color/color_white"
        app:zxing_viewfinder_mask="@color/zxing_custom_viewfinder_mask" />

    <TextView
        android:id="@+id/zxing_status_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="30dp"
        android:background="@color/zxing_transparent"
        android:text="@string/zxing_msg_default_status"
        android:textColor="@color/zxing_status_text" />

    <com.x.common.widget.MyActionBar
        android:id="@+id/action_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:dark_mode="true"
        app:title="扫一扫" />
</merge>

5、

/**
 * 自定义扫描界面
 */

public class QrView extends ViewfinderView {

    public int laserLinePosition = 0;
    public float[] position = new float[]{0f, 0.5f, 1f};
    public int[] colors = new int[]{0x0027B14D, 0xff27B14D, 0x0027B14D};
    public LinearGradient linearGradient;
    private int ScreenRate;

    public QrView(Context context, AttributeSet attrs) {
        super(context, attrs);
        float density = context.getResources().getDisplayMetrics().density;
        ScreenRate = (int) (15 * density);
    }

    @Override
    public void onDraw(Canvas canvas) {
        int CORNER_WIDTH = 15;
        refreshSizes();

        if (framingRect == null || previewFramingRect == null) {
            return;
        }

        Rect frame = framingRect;
        Rect previewFrame = previewFramingRect;

        int width = canvas.getWidth();
        int height = canvas.getHeight();
        //绘制4个角

        paint.setColor(getResources().getColor(R.color.color_white));//定义画笔的颜色
        canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate, frame.top + CORNER_WIDTH, paint);
        canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top + ScreenRate, paint);

        canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right, frame.top + CORNER_WIDTH, paint);
        canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top + ScreenRate, paint);

        canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left + ScreenRate, frame.bottom, paint);
        canvas.drawRect(frame.left, frame.bottom - ScreenRate, frame.left + CORNER_WIDTH, frame.bottom, paint);

        canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH, frame.right, frame.bottom, paint);
        canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate, frame.right, frame.bottom, paint);

        // 画出外部(即构图矩形之外)变暗
        paint.setColor(resultBitmap != null ? resultColor : maskColor);
        canvas.drawRect(0, 0, width, frame.top, paint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom, paint);
        canvas.drawRect(frame.right, frame.top, width, frame.bottom, paint);
        canvas.drawRect(0, frame.bottom, width, height, paint);

        if (resultBitmap != null) {
            // Draw the opaque result bitmap over the scanning rectangle
            paint.setAlpha(CURRENT_POINT_OPACITY);
            canvas.drawBitmap(resultBitmap, null, frame, paint);
        } else {

            laserLinePosition = laserLinePosition + 8;
            if (laserLinePosition >= frame.height()) {
                laserLinePosition = 0;
            }
            linearGradient = new LinearGradient(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, colors, position, Shader.TileMode.CLAMP);
            // Draw a red "laser scanner" line through the middle to show decoding is active

            paint.setShader(linearGradient);
            //绘制扫描线
            canvas.drawRect(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, paint);
            paint.setShader(null);
            float scaleX = frame.width() / (float) previewFrame.width();
            float scaleY = frame.height() / (float) previewFrame.height();

            List<ResultPoint> currentPossible = possibleResultPoints;
            List<ResultPoint> currentLast = lastPossibleResultPoints;
            int frameLeft = frame.left;
            int frameTop = frame.top;
            if (currentPossible.isEmpty()) {
                lastPossibleResultPoints = null;
            } else {
                possibleResultPoints = new ArrayList<>(5);
                lastPossibleResultPoints = currentPossible;
                paint.setAlpha(CURRENT_POINT_OPACITY);
                paint.setColor(resultPointColor);
                for (ResultPoint point : currentPossible) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), POINT_SIZE, paint);
                }
            }
            if (currentLast != null) {
                paint.setAlpha(CURRENT_POINT_OPACITY / 2);
                paint.setColor(resultPointColor);
                float radius = POINT_SIZE / 2.0f;
                for (ResultPoint point : currentLast) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), radius, paint);
                }
            }
            postInvalidateDelayed(16, frame.left, frame.top, frame.right, frame.bottom);
        }
    }
}

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
要给 Android App 增加扫码功能,可以使用第三方库来实现。一个常用的库是 ZXing,它支持多种码的识别,包括二维码和条形码。 要使用 ZXing,首先需要在项目中引入 ZXing 的依赖库。可以在项目的 build.gradle 文件中添加以下代码: ``` implementation 'com.google.zxing:core:3.3.3' ``` 然后,在需要使用扫码功能的界面中添加一个扫码按钮,并在点击事件中调用 ZXing 的扫码功能。以下是一个简单的示例代码: ``` // 定义扫码请求码 private static final int SCAN_REQUEST_CODE = 0; // 扫码按钮点击事件 public void onScanButtonClick(View view) { // 调用扫码功能 Intent intent = new Intent(this, CaptureActivity.class); startActivityForResult(intent, SCAN_REQUEST_CODE); } // 处理扫码结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SCAN_REQUEST_CODE && resultCode == RESULT_OK) { String result = data.getStringExtra(CaptureActivity.EXTRA_RESULT); // 处理扫码结果 } } ``` 这段代码中,onScanButtonClick() 方法中创建了一个 Intent 对象,调用 startActivityForResult() 方法启动扫码界面。扫码界面由 ZXing 的 CaptureActivity 实现,通过 Intent 的方式启动。在 onActivityResult() 方法中处理扫码结果,从 Intent 中获取扫码结果并进行处理。 需要注意的是,使用 ZXing 的扫码功能需要用户授权相机权限,需要在 AndroidManifest.xml 中添加以下代码: ``` <uses-permission android:name="android.permission.CAMERA" /> ``` 另外,需要在 AndroidManifest.xml 中注册 ZXing 的 CaptureActivity: ``` <activity android:name="com.google.zxing.client.android.CaptureActivity" android:screenOrientation="portrait" android:clearTaskOnLaunch="true" android:stateNotNeeded="true" android:theme="@style/AppTheme.NoActionBar" /> ``` 以上是一个简单的示例,具体实现方式还需要根据具体的需求来进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值