如何在 Android 上使用 .NET MAUI 讀取和寫入條碼
.NET MAUI(多平台應用程式 UI)是 Xamarin.Forms 的繼任者,它使開發人員能夠使用 .NET 為 Android、iOS、macOS 和 Windows 建立跨平台應用程式。 它簡化了開發流程,允許創建可在多個平台上無縫運行的原生用戶介面。
BarCode.Android 套件為 Android 提供條碼支援!
如何在 Android 上使用 .NET MAUI 讀取和寫入條碼
IronBarcode Android 套件
BarCode.Android 套件透過 .NET 跨平台專案為 Android 設備提供條碼功能。 不需要預設的條碼軟體包。
使用 NuGet 安裝
安裝 BarCode.Android 套件
建立一個 .NET MAUI 項目
開啟 Visual Studio,然後按一下「建立新專案」。 搜尋 MAUI,選擇 .NET MAUI 應用程式,然後按一下“下一步”。
包含 BarCode.Android 庫
可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。
- 在 Visual Studio 中,右鍵按一下“依賴項”,然後選擇“管理 NuGet 套件...”。
- 選擇「瀏覽」選項卡,搜尋「BarCode.Android」。
- 選擇「BarCode.Android」軟體包,然後點選「安裝」。
為防止與其他平台出現問題,請修改 csproj 文件,使其僅在面向 Android 平台時包含該軟體套件。 為了做到這一點:
-
右鍵點選專案的 *.csproj 文件,然後選擇「編輯專案文件」。
-
建立一個新的 ItemGroup 元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> <PackageReference Include="BarCode.Android" Version="2025.3.4" /> </ItemGroup>XML -
將「BarCode.Android」PackageReference 移到我們剛剛建立的 ItemGroup 中。
上述步驟將阻止「BarCode.Android」軟體包在iOS等平台上使用。 為此請安裝 BarCode.iOS。
配置 Android Bundle
要讓 Android 系統正常運作,需要配置 Android 軟體包設定。 在您的「.csproj」檔案中,新增以下條目以指定Android套件的設定檔:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
在專案根目錄下建立一個名為「BundleConfig.json」的檔案。 此 JSON 檔案包含 Android 套件所需的設置,這些設置對於程式庫的功能至關重要。
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
此配置可確保本機庫未壓縮,這是庫在 Android 環境中正常運作的必要步驟。
設計應用程式介面
更新 XAML 文件,允許使用者輸入值以產生條碼和二維碼。 此外,新增一個按鈕,用於選擇要讀取條碼的文件。 以下是一個範例:
<?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>
讀寫條碼
從上面的 MainPage.xaml 程式碼可以看出,該複選框決定產生的條碼和二維碼是否應為 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);
}
}
}
}Imports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(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")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(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")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End NamespaceImports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(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")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(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")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End Namespace運行專案
這將向您展示如何運行項目和使用條碼功能。
下載 .NET MAUI 應用程式項目
您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案開啟。
常見問題
.NET MAUI是什麼以及它如何與Android的條碼掃描相關?
.NET MAUI,全稱多平台應用 UI,是Xamarin.Forms的繼任者,允許開發者構建跨平台應用。BarCode.Android套件與.NET MAUI整合,能在Android設備上實現條碼讀寫。
如何將BarCode.Android程式庫添加到我的.NET MAUI專案中?
您可以使用Visual Studio中的NuGet來添加BarCode.Android程式庫。右鍵單擊 'Dependencies',選擇 'Manage NuGet Packages',搜尋 'BarCode.Android',然後點擊 '安裝'。
BarCode.Android套件可以用於除Android以外的平台嗎?
BarCode.Android套件專為Android量身定制。對於iOS,您需要使用BarCode.iOS套件。
如何配置專案以僅在Android中包含BarCode.Android程式庫?
您應該編輯您的.csproj文件,以在目標為Android時使用TargetFramework條件包含BarCode.Android套件的條件ItemGroup。
我是否需要特定的配置文件來在Android上使用BarCode.Android程式庫?
是的,您需要在您的.csproj文件中為Android包指定通常名為 'BundleConfig.json' 的配置文件,以確保原生程式庫未被壓縮。
如何在MAUI應用中使用IronBarcode生成並保存條碼?
您可以使用BarcodeWriter類從文本輸入創建條碼,決定格式(PDF或PNG),然後使用類似SaveToDownloadsAsync方法保存到Android和iOS。
IronBarcode支持哪些文件格式用於保存生成的條碼?
IronBarcode允許條碼以PDF或PNG格式保存,基於使用者在應用中的選擇。
IronBarcode如何在.NET MAUI的Android應用中幫助處理QR碼?
IronBarcode透過QRCodeWriter類協助QR碼的創建與讀取,實現從輸入文字生成QR碼以及從文件讀取條碼數據的功能。
是否有可用的範例專案以開始使用IronBarcode於.NET MAUI中?
是的,您可以下載一個完整的.NET MAUI應用專案,裡面包含指南提供的範例代碼以快速開始。
IronBarcode提供了哪些功能來從文件讀取條碼數據?
IronBarcode可以使用BarcodeReader類從圖像和PDF文件中讀取條碼,結果將在應用中格式化顯示。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。