Androidでバーコードスキャン機能を実装する方法【ZXingライブラリ活用】
本記事では、Androidアプリにバーコードスキャン機能を実装する方法を、ステップごとにわかりやすく解説します。Googleが提供するオープンソースの「ZXing(Zebra Crossing)」ライブラリを使用することで、QRコードをはじめとする各種バーコードを簡単に読み取れるようになります。
ステップ1:Android Studioで新規プロジェクトを作成する
まず、Android Studioを起動し、メニューから「File → New Project」を選択して新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存先など)をすべて入力してプロジェクトをセットアップしましょう。
ステップ2:レイアウトファイル(activity_main.xml)を編集する
次に、res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、スキャンを開始するためのボタンと、読み取り結果を表示するテキストビューを配置しています。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:layout_below="@id/button"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp"
android:text="code reader"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtContent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Process"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
</RelativeLayout>ステップ3:Gradleに依存関係を追加する
バーコード読み取りに必要なZXingライブラリを利用できるよう、build.gradle ファイルに以下の依存関係を追加します。
implementation 'com.google.zxing:core:3.2.1' implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
「zxing-android-embedded」は、ZXingのコア機能をAndroid向けに組み込みやすくしたラッパーライブラリです。これにより、カメラプレビュー画面やスキャン処理を自前で実装する手間が省けます。
ステップ4:MainActivity.javaにコードを記述する
src/MainActivity.java に以下のコードを追加します。ボタンをタップするとIntentIntegratorが起動し、カメラによるスキャンが開始されます。読み取り結果は onActivityResult() で受け取り、トーストとテキストビューに表示されます。
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class MainActivity extends AppCompatActivity {
Button btnBarcode;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBarcode = findViewById(R.id.button);
textView = findViewById(R.id.txtContent);
btnBarcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES);
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setCameraId(0);
intentIntegrator.setPrompt("SCAN");
intentIntegrator.setBarcodeImageEnabled(false);
intentIntegrator.initiateScan();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult Result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (Result != null) {
if (Result.getContents() == null) {
Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show();
textView.setText(String.format("Scanned Result: %s", Result));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}ステップ5:AndroidManifest.xmlに権限を設定する
最後に、androidManifest.xml に以下のコードを追加します。カメラを使用するため、CAMERA権限の宣言が必要です。忘れるとアプリがクラッシュする原因になるので注意してください。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-feature android:name="android.hardware.camera.autoFocus" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>アプリを実行して動作を確認する
ここまでの設定が完了したら、実際にアプリを起動してみましょう。実機のAndroidスマートフォンをPCに接続していることを確認し、Android Studioでアクティビティファイルを開いて、ツールバーの「Run」アイコンをクリックします。デバイス選択画面で接続した端末を選択すると、アプリがインストールされ、初期画面が表示されます。
ボタンをタップするとカメラが起動し、バーコードやQRコードを読み取ると結果が画面に表示されます。エミュレータではカメラの動作が制限される場合があるため、より正確な検証のためには実機でのテストをおすすめします。
-
AndroidでsynchronizedSortedSetを使う方法をわかりやすく解説【サンプルコード付き】
はじめにこの記事では、Androidアプリ開発においてCollections.synchronizedSortedSetを使用する方法を、実際のサンプルコードを交えながらステップごとに解説します。synchronizedSortedSetは、スレッドセーフなSortedSet(ソート済みセット)を生成するための仕組みです。複数のスレッドから同時にアクセスされる可能性があるデータを扱う際に、要素が自動的にソートされつつ、安全に操作できるようになります。本記事のサンプルでは、ユーザーが名前を入力して保存すると、TreeSet(自動的にソートされるセット)に追加され、その内容が同期化されたSorte
-
【Android入門】ToggleButton(トグルボタン)の使い方と実装例をわかりやすく解説
ToggleButtonとは 実装例に入る前に、AndroidにおけるToggleButton(トグルボタン)について簡単に確認しておきましょう。ToggleButtonはButtonビューを拡張したウィジェットで、ボタンの状態を「チェック済み(ON)」と「未チェック(OFF)」の2つの状態として表現できます。設定の有効・無効を切り替えるなど、オン・オフ操作が必要な場面で活躍するUIパーツです。 ここからは、AndroidアプリでToggleButtonを実装する具体的な手順をステップごとに見ていきます。 ステップ1:新規プロジェクトを作成する Android Studioで新しいプロジェクト