LoginSignup
81
96

More than 3 years have passed since last update.

QRコードの読取、生成をする [Android]

Last updated at Posted at 2018-04-21

開発環境

OS: macOS HighSierra
Android Studio: 3.0.1

・APIレベルの設定

build.gradle
android {
    compileSdkVersion 26
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 26
        }
}

ライブラリの導入

使用するライブラリ:
zxing-android-embedded (3.6.0)
https://github.com/journeyapps/zxing-android-embedded

プロジェクトへの追加方法:
build.gradle (Module: app)に以下の一文を追加する。

build.gradle
dependencies {
    ...
    compile 'com.journeyapps:zxing-android-embedded:3.6.0'
}

QRコードの読み取り

読み取り用カメラの起動


new IntentIntegrator(MainActivity.this).initiateScan();

読み取り処理をしたいところに上記のコードを記述する。
MainActivity.thisの部分は対象のActivity名に変更して使う。

読み取った結果の取得

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            Log.d("readQR", result.getContents());
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

読み取ったデータをgetContents()でString型で受け取ることができる。

QRコードの生成

//QRコード化する文字列
String data = "https://www.google.com";
//QRコード画像の大きさを指定(pixel)
int size = 500;


try {
    BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
    //QRコードをBitmapで作成
    Bitmap bitmap = barcodeEncoder.encodeBitmap(data,BarcodeFormat.QR_CODE, size, size);

    //作成したQRコードを画面上に配置
    ImageView imageViewQrCode = (ImageView) findViewById(R.id.imageView);
    imageViewQrCode.setImageBitmap(bitmap);

} catch (WriterException e) {
    throw new AndroidRuntimeException("Barcode Error.", e);
}

dataの中身がQRコードに反映される。
sizeで画像の大きさを指定する。

Acticityに対応するxmlファイルでImageViewを用意しておき、
Bitmapで作成したQRコードを配置し、画面に表示する。

<文字コードや、誤り訂正レベル、QRコードのバージョン等を指定したい場合>


String data = "https://www.google.com"; //QRコード化する文字列
//QRコード画像の大きさを指定(pixel)
int size = 500;

try {
    BarcodeEncoder barcodeEncoder = new BarcodeEncoder();

    HashMap hints = new HashMap();

    //文字コードの指定
    hints.put(EncodeHintType.CHARACTER_SET, "shiftjis");

    //誤り訂正レベルを指定
        //L 7%が復元可能
        //M 15%が復元可能
        //Q 25%が復元可能
        //H 30%が復元可能
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

    //QRコードのバージョンを指定
    hints.put(EncodeHintType.QR_VERSION, 20);

    Bitmap bitmap = barcodeEncoder.encodeBitmap(data, BarcodeFormat.QR_CODE, size, size, hints);

    ImageView imageViewQrCode = (ImageView) findViewById(R.id.imageView);
    imageViewQrCode.setImageBitmap(bitmap);

} catch (WriterException e) {
    throw new AndroidRuntimeException("Barcode Error.", e);
}

EncodeHintTypeを使用して細かい指定をしつつQRコードを作成できる。

81
96
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
81
96