안드로이드 QR코드 기능 통합

안드로이드 QR코드 기능 통합
           https://github.com/journeyapps/zxing-android-embedded

이 라이브러리는 zxing에 대해 직접 봉인 추출을 진행하여 사용하기에도 비교적 편리하다.사용자 정의 인터페이스의 실현도 매우 쉽다.다음은 코드를 보십시오.
 build.gradle          
    repositories {
    jcenter()
}

dependencies {
    compile 'com.journeyapps:zxing-android-embedded:3.3.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    compile 'com.android.support:appcompat-v7:23.1.0'   // Version 23+ is required
}

android {
    buildToolsVersion '23.0.2' // Older versions may give compile errors
}
/**
     *           
     */

    @Override
    public void jumpToScanCode() {
        iv_jump_to_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentIntegrator integrator = IntentIntegrator.forSupportFragment(ConnectWifiFragment.this).setCaptureActivity(CustomCaptureAvtivity.class);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setPrompt("       ");
                integrator.setCameraId(0);  // Use a specific camera of the device
                integrator.setBeepEnabled(false);
                integrator.setBarcodeImageEnabled(true);
                integrator.setOrientationLocked(false);
                integrator.initiateScan();

            }
        });
    }

여기fragment의 한 단추에서 새로운 avtivity 창을 열고 QR코드를 스캔합니다. QR코드를 스캔하는 창은 사용자 정의Custom Capture Avtivity를 사용합니다.이 라이브러리에서 제공하는 스캔 창을 사용하면 set Capture Activity (Custom Capture Avtivity.class) 방법을 추가하지 않아도 됩니다.스캔 상자의 모양 크기를 사용자 정의해야 하기 때문에 CustomCaptureAvtivity를 사용자 정의합니다.
 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
            } else {
                Intent intent = new Intent(getActivity(), QRCodeActivity.class);
                intent.putExtra(Constant.ScanFinishJumpToUrl,result.getContents());
                startActivity(intent);
            }

            // At this point we may or may not have a reference to the activity
          //  displayToast();
        }
    }

onActivity Result에서 스캔한 결과를 받을 수 있습니다. 여기에서 스캔 결과를 받은 후 QR코드 스캔 결과를 열고 돌아오는 사이트로 액티브를 돌렸습니다.기본 스캐너 인터페이스로 여기까지 오면 성공했어.
public class CustomCaptureAvtivity extends Activity implements DecoratedBarcodeView.TorchListener ,View.OnClickListener {

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private Button switchFlashlightButton;
    private ImageView iv_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_capture_avtivity);

        barcodeScannerView = (DecoratedBarcodeView)findViewById(R.id.zxing_barcode_scanner);
        iv_back = (ImageView)findViewById(R.id.iv_scan_back);
        barcodeScannerView.setTorchListener(this);
        iv_back.setOnClickListener(this);
        // if the device does not have flashlight in its camera,
        // then remove the switch flashlight button...
        if (!hasFlash()) {
            switchFlashlightButton.setVisibility(View.GONE);
        }

        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);
        capture.decode();
    }

    @Override
    protected void onResume() {
        super.onResume();
        capture.onResume();
    }

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

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

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

    /**
     * Check if the device's camera has a Flashlight.
     * @return true if there is Flashlight, otherwise false.
     */
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    public void switchFlashlight(View view) {

    }

    @Override
    public void onTorchOn() {
       // switchFlashlightButton.setText(R.string.turn_off_flashlight);
    }

    @Override
    public void onTorchOff() {
      //  switchFlashlightButton.setText(R.string.turn_on_flashlight);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_scan_back:
                CustomCaptureAvtivity.this.finish();
                break;
        }

        }

}

이것은 데모 안의 사용자 정의 스캐너 인터페이스의activity로 고스란히 베껴서 고친 것이 있다.주로 스캔 인터페이스가 초기화되었습니다.
public class CustomViewfinderView extends ViewfinderView {
    public int laserLinePosition=0;
    public float[] position=new float[]{0f,0.5f,1f};
    public int[] colors=new int[]{0x00ffffff,0xffffffff,0x00ffffff};
    public  LinearGradient linearGradient ;
    public CustomViewfinderView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    /**
     *   draw          
     * @param canvas
     */
    @Override
    public void onDraw(Canvas canvas) {
        refreshSizes();
        if (framingRect == null || previewFramingRect == null) {
            return;
        }

        Rect frame = framingRect;
        Rect previewFrame = previewFramingRect;

        int width = canvas.getWidth();
        int height = canvas.getHeight();
        //  4  

        paint.setColor(0xFFFFFFFF);
        canvas.drawRect(frame.left, frame.top, frame.left+70, frame.top+10, paint);
        canvas.drawRect(frame.left, frame.top, frame.left + 10, frame.top + 70, paint);

        canvas.drawRect(frame.right-70, frame.top, frame.right, frame.top+10, paint);
        canvas.drawRect(frame.right-10, frame.top, frame.right, frame.top+70, paint);

        canvas.drawRect(frame.left, frame.bottom-10, frame.left+70, frame.bottom, paint);
        canvas.drawRect(frame.left, frame.bottom-70, frame.left+10, frame.bottom, paint);

        canvas.drawRect(frame.right-70, frame.bottom-10, frame.right, frame.bottom, paint);
        canvas.drawRect(frame.right-10, frame.bottom-70, frame.right, frame.bottom, paint);
        // Draw the exterior (i.e. outside the framing rect) darkened
        paint.setColor(resultBitmap != null ? resultColor : maskColor);
        canvas.drawRect(0, 0, width, frame.top, paint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
        canvas.drawRect(0, frame.bottom + 1, 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 {


          //  paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
          //  scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
            int middle = frame.height() / 2 + frame.top;
            laserLinePosition=laserLinePosition+5;
            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.setColor(laserColor);
            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 currentPossible = possibleResultPoints;
            List 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);
           // postInvalidate();

        }
    }
}

안에 있는 이 ViewfinderView 클래스는 QR코드를 스캔하는 데 사용되는 것으로 QR코드 스캔 인터페이스의 전체 스캔 상자의 외형을 결정한다. 나는 여기에서 그의 다른 논리를 바꾸지 않고 스캔 인터페이스를 다시 그릴 필요가 있다. 여기서 나는 사용자 정의 클래스를 선택하여 ViewfinderView를 계승하고 그의 ondraw 방법을 다시 써서 자신의 스캔 상자를 그린다.물론 레이아웃 파일에서 레이아웃 파일의 내용을 수정하는 것을 잊지 마세요.
//CustomCaptureAvtivity    
"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.zxing.CustomScannerActivity">

    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/zxing_barcode_scanner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_scanner_layout="@layout/custom_barcode_scanner">
    com.journeyapps.barcodescanner.DecoratedBarcodeView>

    "match_parent"
        android:layout_height="48dp"
        android:padding="10dp"
        android:background="#cc333333"
        >
        "@+id/iv_scan_back"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/home_btn_back"
            />
    

//CustomCaptureAvtivity           ,   
<com.e7wifi.colourmedia.view.CustomViewfinderView>     CustomViewfinderView

"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       xmlns:app="http://schemas.android.com/apk/res-auto">

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

    <com.e7wifi.colourmedia.view.CustomViewfinderView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/zxing_viewfinder_view"
        app:zxing_possible_result_points="@color/zxing_custom_possible_result_points"
        app:zxing_result_view="@color/zxing_custom_result_view"
        app:zxing_viewfinder_laser="#FFFFFF"
        app:zxing_viewfinder_mask="@color/zxing_custom_viewfinder_mask"/>

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

좋은 웹페이지 즐겨찾기