.NET MAUI で Android のバーコードを読み書きする方法

This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to .NET MAUI で Android のバーコードを読み書きする方法

.NET MAUI (Multi-platform App UI)はXamarin.Formsの後継であり、開発者が.NETを使用してAndroid、iOS、macOS、Windows用のクロスプラットフォームアプリケーションを構築できるようにします。 これは、複数のプラットフォームでシームレスに動作するネイティブユーザーインターフェイスの作成を可能にすることにより、開発プロセスを合理化します。

BarCode.Androidパッケージは、Androidにバーコードサポートをもたらします!

IronBarcode Android パッケージ

BarCode.Androidパッケージは、.NETクロスプラットフォームプロジェクトを通じてAndroidデバイスにバーコード機能を提供します。 バニラのBarCodeパッケージは必要ありません。

インストールパッケージ BarCode.Android
PDF用C# NuGetライブラリ

Install with NuGet

インストールパッケージ BarCode.Android

.NET MAUIプロジェクトの作成

Visual Studioを開き、"新しいプロジェクトを作成"をクリックします。 MAUIを検索し、.NET MAUIアプリを選択して"次へ"をクリックします。

BarCode.Androidライブラリを含める

ライブラリを追加する方法はいくつかあります。 最も簡単なのは、おそらくNuGetを使用することです。

  1. Visual Studio内で"Dependencies"を右クリックし、"Manage NuGet Packages ..."を選択します。
  2. "Browse"タブを選択して"BarCode.Android"を検索します。
  3. "BarCode.Android"パッケージを選択して"インストール"をクリックします。

他のプラットフォームとの問題を避けるために、csprojファイルを修正して、Androidプラットフォームをターゲットにした場合だけパッケージを含めるようにします。 これを行うには:

  1. プロジェクトの*.csprojファイルを右クリックして"プロジェクトファイルを編集"を選択します。
  2. 新しいItemGroup要素を作成します。
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. "BarCode.Android"のPackageReferenceを作成したItemGroup内に移動します。

上記の手順により、iOSなどのプラットフォームでは"BarCode.Android"パッケージが使用されることはありません。 その目的のために、BarCode.iOSを代わりにインストールしてください。

Androidバンドルを構成する

Androidが動作するには、Androidバンドルの設定を構成する必要があります。 ".csproj"ファイル内に、Androidバンドルの設定ファイルを指定するための次のエントリを追加してください:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

プロジェクトのルートディレクトリに"BundleConfig.json"という名前のファイルを作成します。 このJSONファイルには、Androidバンドルに必要な設定が含まれており、ライブラリの機能にとって重要です。

{
    "optimizations": {
        "uncompress_native_libraries": {}
    }
}

この設定により、ネイティブライブラリが圧縮されず、Android環境でライブラリが正常に動作するために必要なステップとなります。

アプリインターフェースを設計する

XAMLファイルを更新して、ユーザーがバーコードおよびQRコードを生成するための値を入力できるようにします。 さらに、バーコード読み取り用のドキュメントを選択するボタンを追加します。 こちらが例です:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiAndroid.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
            Text="Read Barcode"
            Clicked="ReadBarcode"
            Grid.Row="0"
            HorizontalOptions="Center"
            Margin="20, 20, 20, 10"/>
        <ScrollView
            Grid.Row="1"
            BackgroundColor="LightGray"
            Padding="10"
            Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiAndroid.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
            Text="Read Barcode"
            Clicked="ReadBarcode"
            Grid.Row="0"
            HorizontalOptions="Center"
            Margin="20, 20, 20, 10"/>
        <ScrollView
            Grid.Row="1"
            BackgroundColor="LightGray"
            Padding="10"
            Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
XML

バーコードを読み書きする

上記のMainPage.xamlコードから、チェックボックスが生成されたバーコードおよびQRコードがPDF形式であるかどうかを決定することがわかります。 次に、ライセンスキーを設定します。 このステップでは、試用版または有料ライセンスキーのいずれかを使用してください。

コードはbarcodeInput変数から値を調べて取得し、その後CreateBarcodeメソッドを使用してバーコードを生成します。 最後に、SaveToDownloadsAsyncメソッドを呼び出し、AndroidおよびiOSの両方に適切にファイルを保存します。

iOSでは、カスタムファイルパスが必要であり、Filesアプリケーションにドキュメントをエクスポートします。

using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            // Set the license key for IronBarcode, replace with your actual license key.
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    // Create a barcode from the text input with the EAN13 encoding.
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated barcode to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    // Create a QR code from the text input.
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated QR code to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void ReadBarcode(object sender, EventArgs e)
        {
            try
            {
                var options = new PickOptions
                {
                    PickerTitle = "Please select a file"
                };
                var file = await FilePicker.PickAsync(options);

                OutputText.Text = "";

                if (file != null)
                {
                    using var stream = await file.OpenReadAsync();

                    BarcodeResults result;

                    if (file.ContentType.Contains("image"))
                    {
                        // Read barcodes from an image file.
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        // Read barcodes from a PDF file.
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    // Retrieve and format the barcode reading results.
                    result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
            var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);

            try
            {
                // Create the directory if it doesn't exist.
                if (!Directory.Exists(downloadsPath.AbsolutePath))
                {
                    Directory.CreateDirectory(downloadsPath.AbsolutePath);
                }

                // Save the file to the Downloads folder.
                await File.WriteAllBytesAsync(filePath, fileData);
            }
            catch (Exception ex)
            {
                // Log errors if file saving fails.
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
        }
    }
}
using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            // Set the license key for IronBarcode, replace with your actual license key.
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    // Create a barcode from the text input with the EAN13 encoding.
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated barcode to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    // Create a QR code from the text input.
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated QR code to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void ReadBarcode(object sender, EventArgs e)
        {
            try
            {
                var options = new PickOptions
                {
                    PickerTitle = "Please select a file"
                };
                var file = await FilePicker.PickAsync(options);

                OutputText.Text = "";

                if (file != null)
                {
                    using var stream = await file.OpenReadAsync();

                    BarcodeResults result;

                    if (file.ContentType.Contains("image"))
                    {
                        // Read barcodes from an image file.
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        // Read barcodes from a PDF file.
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    // Retrieve and format the barcode reading results.
                    result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
            var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);

            try
            {
                // Create the directory if it doesn't exist.
                if (!Directory.Exists(downloadsPath.AbsolutePath))
                {
                    Directory.CreateDirectory(downloadsPath.AbsolutePath);
                }

                // Save the file to the Downloads folder.
                await File.WriteAllBytesAsync(filePath, fileData);
            }
            catch (Exception ex)
            {
                // Log errors if file saving fails.
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
        }
    }
}
$vbLabelText   $csharpLabel

プロジェクトを実行する

これにより、プロジェクトを実行してバーコード機能を使用する方法が示されます。

Execute .NET MAUI App project

.NET MAUIアプリプロジェクトをダウンロードする

このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。

プロジェクトをダウンロードするにはここをクリックしてください。

よくある質問

.NET MAUIアプリでAndroid向けにバーコードを作成しスキャンするにはどうすればよいですか?

.NET MAUIプロジェクト内でBarCode.Androidパッケージを使用してAndroidデバイス上でバーコードを作成しスキャンすることができます。これには、Visual Studioを通じてNuGetでパッケージを設定し、提供されたWriteBarcodeReadBarcodeなどのメソッドを使用したバーコード機能の実装が含まれます。

Android用に.NET MAUIプロジェクトでバーコード機能を設定するために必要な手順は何ですか?

.NET MAUIプロジェクトでのバーコード機能の設定には、NuGetを使用してBarCode.Androidパッケージをインストールし、csprojファイルを編集してAndroidに対して条件付きでパッケージを含めるように構成し、BundleConfig.jsonファイルを通じてAndroidバンドルを設定することが含まれます。

バーコード機能をAndroidのみで含めるためにcsprojファイルをどのように設定しますか?

.csprojファイルを編集して、Androidをターゲットにした条件を持つを追加します。このグループ内にBarCode.Androidパッケージを含めることで、バーコード機能がAndroidビルドにのみ追加されるようにします。

AndroidプロジェクトでBundleConfig.jsonファイルを使用する目的は何ですか?

BundleConfig.jsonファイルは、ネイティブライブラリが圧縮されないようにAndroidバンドル設定を構成するために使用されます。これは、Androidデバイス上でバーコードライブラリが正しく機能するために不可欠です。

.NET MAUIアプリでバーコード操作のインターフェイスはどのようにデザインできますか?

XAMLを使用してアプリのインターフェースをデザインし、ユーザーがバーコードおよびQRコードを生成するためのデータを入力できるようにします。バーコードを読み取るためのドキュメントを選択するボタンや、バーコードを生成、保存、スキャンするためのボタンを含めます。

アプリでバーコードを生成し読み取るためにC#で使用されるメソッドは何ですか?

.NET MAUIアプリで、WriteBarcodeWriteQRcode、およびReadBarcodeなどのメソッドを使用して、バーコードを生成し、QRコードを作成し、ファイルからバーコードを読み取ります。

.NET MAUIアプリでバーコード機能をどのようにテストできますか?

必要な設定とバーコードコードの実装が完了したら、Visual Studioを通じてAndroidデバイスまたはエミュレータでプロジェクトを実行することで機能をテストできます。

バーコード機能を備えた完全な.NET MAUIアプリプロジェクトはどこで見つけられますか?

バーコード機能を備えた完全な.NET MAUIアプリプロジェクトは、IronBarcodeのウェブサイトからジップ形式でダウンロードできます。このプロジェクトはVisual Studioで開いてさらに探求したりカスタマイズすることができます。

Androidプロジェクトでバーコードライブラリを使用するにはライセンスが必要ですか?

はい、プロジェクトでバーコードライブラリを使用するには、トライアルまたは有料のライセンスキーが必要です。このキーをMainPageコンストラクターに入力して、ライブラリの機能をアクティブにする必要があります。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 2,035,202 | バージョン: 2025.12 リリース