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

掃一掃和二維碼

掃一掃

匯入

repositories {

    mavenCentral()

    maven {

        url "http://dl.bintray.com/journeyapps/maven"

    }

}
implementation 'com.journeyapps:zxing-android-embedded:[email protected]'
    implementation 'com.journeyapps:zxing-android-legacy:[email protected]'
    implementation 'com.journeyapps:zxing-android-integration:
[email protected]
'

xml

<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".activity.TwoActivity"
    android:gravity="center">
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:src="@drawable/ic_launcher_background" />

    <Button
        android:id="@+id/tuichu_btn"
        android:layout_width="match_parent"
        android:layout_marginTop="15dp"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="退出登入" />
    <Button
        android:id="@+id/sao_btn"
        android:layout_marginTop="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="掃一掃"/>

</LinearLayout>

java

package com.example.zhoukao.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.zhoukao.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

public class TwoActivity extends AppCompatActivity {

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        ImageView iamge = findViewById(R.id.image);
        Button button = findViewById(R.id.tuichu_btn);
        Button button1 = findViewById(R.id.sao_btn);
        sp = getSharedPreferences("login", MODE_PRIVATE);
        String name = sp.getString("name", "");
        Bitmap bitmap = createQRImage(name, 200, 200);
        iamge.setImageBitmap(bitmap);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(TwoActivity.this, MainActivity.class));
                finish();
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(TwoActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    IntentIntegrator integrator = new IntentIntegrator(TwoActivity.this);
                    integrator.initiateScan();
                } else {
                    ActivityCompat.requestPermissions(TwoActivity.this, new String[]{Manifest.permission.CAMERA}, 100);
                }
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(TwoActivity.this, "許可權開啟", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            Log.d("code", result);
//變數result就是二維碼解碼後的資訊。
            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        }
    }
    public static Bitmap createQRImage(String url, final int width, final int height) {
        try {
            // 判斷URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 影象資料轉換,使用了矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            // 下面這裡按照二維碼的演算法,逐個生成二維碼的圖片,
            // 兩個for迴圈是圖片橫列掃描的結果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            // 生成二維碼圖片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}