zxing第三方框架實現二維碼掃描以及生成

ren18234073466發表於2018-12-03
二維碼需要的依賴:implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.3.4'
二維碼需要的許可權: <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

MainActivity

package com.example.qrcode;

import android.Manifest;
import android.content.ContentProvider;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class MainActivity extends AppCompatActivity {
    private Button scanning_code,generate_code;
    private ImageView imageView;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取資源id
        scanning_code=findViewById(R.id.scanning_code);
        generate_code=findViewById(R.id.generate_code);
        imageView=findViewById(R.id.image);
        editText=findViewById(R.id.edit_text);
        //掃描二維碼的點選事件
        scanning_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判斷android版本號是否是6.0以上,(Build.VERSION_CODES.M:表示版本號是6.0)
                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                    //checkSelfPermission判斷當前有沒有第二個引數所代表的許可權,當前許可權為相機許可權
                    //如果與給定條件不同,這沒有此許可權。需要授權
                    if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){

                        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA},100);

                    }  else{
                        //如果版本是6.0以上,且條件滿足,授權,直接跳轉
                        Intent intent = new Intent(MainActivity.this,CodeActivity.class);
                        startActivity(intent);
                    }
                }else{
                    //版本低於6.0,直接跳轉,通過清單檔案配置請求許可權
                    Intent intent = new Intent(MainActivity.this,CodeActivity.class);
                    startActivity(intent);
                }

            }
        });
        //生成二維碼的點選事件
        generate_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QRTask qrTask = new QRTask(MainActivity.this,imageView);
                qrTask.execute(editText.getText().toString());
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==100&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
            startActivity(new Intent(MainActivity.this, CodeActivity.class));
        }
    }
    //建立靜態內部類處理文字框獲取到的字串,並生成二維碼賦值與imageview展示
    static class QRTask extends AsyncTask<String,Void,Bitmap>{
        //軟引用型別
        private WeakReference<Context> mContent;
        private WeakReference<ImageView> mImageView;

        public QRTask(Context content,ImageView imageView ) {
            mContent=new WeakReference<>(content);
            mImageView=new WeakReference<>(imageView);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String str = strings[0];
            if (TextUtils.isEmpty(str)){
                return null;
            }
            //軟應用只能通過get()獲取到相應的方法,返回要生成的二維碼的尺寸大小
            int size = mContent.get().getResources().getDimensionPixelOffset(R.dimen.qr_code_size);
            //返回生成的二維碼圖片
            return QRCodeEncoder.syncEncodeQRCode(str,size);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //生成的二維碼不為空就直接賦值與imageview上
            if (bitmap!=null){
                mImageView.get().setImageBitmap(bitmap);
            }else{
                Toast.makeText(mContent.get(),"生成失敗",Toast.LENGTH_SHORT).show();
            }
        }
    }


}

對應的佈局activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/scanning_code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="掃描二維碼"
        />
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/scanning_code"/>
    <Button
        android:id="@+id/generate_code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成二維碼"
        app:layout_constraintTop_toBottomOf="@id/edit_text"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/generate_code"
        android:background="@mipmap/ic_launcher"/>



</android.support.constraint.ConstraintLayout>

CodeActivity掃描二維碼

package com.example.qrcode;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class CodeActivity extends AppCompatActivity implements QRCodeView.Delegate {
    private ZXingView zXingView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.code_item);
        //獲取資源id
        zXingView=findViewById(R.id.zxing);
        zXingView.setDelegate(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //開啟相機
        zXingView.startCamera();
        //顯示掃描框
        zXingView.startSpotAndShowRect();
        // zXingView.openFlashlight();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //關閉相機
        zXingView.stopCamera();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //銷燬
        zXingView.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i("TAG",result);
        Intent intent = new Intent(CodeActivity.this,WebActivity.class);
        intent.putExtra("result",result);
        startActivity(intent);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }
}

對應的佈局code_item

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <cn.bingoogolapple.qrcode.zxing.ZXingView
        android:id="@+id/zxing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></cn.bingoogolapple.qrcode.zxing.ZXingView>
</android.support.constraint.ConstraintLayout>

WebActivity

package com.example.qrcode;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;

public class WebActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_item);
        Intent intent=getIntent();
        String result = intent.getStringExtra("result");
        WebView webView = findViewById(R.id.webview);
        webView.loadUrl(result);
       // webView.loadDataWithBaseURL(null,result,"Text/html","utf-8",null);
    }
}

佈局web_item

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>

相關文章