1. 程式人生 > >生成二維碼 和 掃描二維碼

生成二維碼 和 掃描二維碼

導依賴

implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.3.4'

許可權

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="qr_code_size">200dp</dimen>
</resources>

MainActivity

public class MainActivity extends AppCompatActivity {

    private ImageView mimageView;
    private EditText meditText;
    private Button create,scan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        //點選生成
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createQRCode();
            }
        });
        //點選掃描
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission();
            }
        });

    }

    private void checkPermission() {
        //第一步,判斷系統版本是否為6.0以上
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //第二步:checkSelfPermission判斷有沒有此許可權
            //第一個引數:上下文
            //第二個引數:我們想要判斷的許可權,此處為相機許可權
            //PackageManager.PERMISSION_GRANTED 條件,許可權有沒有被授予
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //如果沒授予,則申請許可權
                //第一個:上下文
                //第二個:要申請的許可權陣列,此處為相機許可權
                //第三個:請求碼,startActivityForResult一樣
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},100);
            }
        }else{
            startActivity(new Intent(MainActivity.this, ScanActivity.class));
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //如果requestCode匹配,切許可權申請通過
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            startActivity(new Intent(MainActivity.this, ScanActivity.class));
        }
    }
    private void createQRCode() {
        QRTask qrTask = new QRTask(this, mimageView, meditText);
        qrTask.execute(meditText.getText().toString());
    }

    private void initView() {
        meditText=findViewById(R.id.edit);
        mimageView=findViewById(R.id.image);
        scan=findViewById(R.id.scan);
        create=findViewById(R.id.create);
    }
    static class QRTask extends AsyncTask<String,Void,Bitmap>{
        private WeakReference<Context> mContext;
        private WeakReference<ImageView> mImageView;

        public QRTask(Context context,ImageView imageView,EditText editText) {
            mContext=new WeakReference<>(context);
            mImageView=new WeakReference<>(imageView);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String str=strings[0];
            if(TextUtils.isEmpty(str)){
                return null;
            }
            int size=mContext.get().getResources().getDimensionPixelOffset(R.dimen.qr_code_size);
            return QRCodeEncoder.syncEncodeQRCode(str,size);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                mImageView.get().setImageBitmap(bitmap);
            } else {
                Toast.makeText(mContext.get(), "生成失敗", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

activity_main.xml

<?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/scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="掃描"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/scan"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />
    <Button
        android:id="@+id/create"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成"
        app:layout_constraintTop_toBottomOf="@+id/edit"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/create"
        android:src="@mipmap/ic_launcher"
        />

</android.support.constraint.ConstraintLayout>

ScanActivity掃碼跳轉

public class ScanActivity extends AppCompatActivity implements QRCodeView.Delegate {

    private ZXingView mZXingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        mZXingView = findViewById(R.id.zxingview);
        mZXingView.setDelegate(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mZXingView.startCamera();
        mZXingView.startSpotAndShowRect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mZXingView.stopCamera();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mZXingView.onDestroy();
        Toast.makeText(ScanActivity.this,11+"",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        if(result!=null){
            Intent intent=new Intent(ScanActivity.this,ContentActivity.class);
            intent.putExtra("result",result);
            startActivity(intent);
        }
        Toast.makeText(ScanActivity.this,result,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }
}

activity_scan.xml

<?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=".ScanActivity">
    <cn.bingoogolapple.qrcode.zxing.ZXingView
        android:id="@+id/zxingview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

展示二維碼內容頁面

public class ContentActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        textView=findViewById(R.id.text);
        Intent intent=getIntent();
        textView.setText(intent.getStringExtra("result"));
    }
}

activity_content.xml 

<?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=".ContentActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>