Lesen und Schreiben von BarCodes auf Android in .NET MAUI
.NET MAUI (Multi-platform App UI) ist der Nachfolger von Xamarin.Forms und ermöglicht es Entwicklern, plattformübergreifende Anwendungen für Android, iOS, macOS und Windows mit .NET zu erstellen. Es vereinfacht den Entwicklungsprozess, indem es die Erstellung von nativen Benutzeroberflächen ermöglicht, die nahtlos über mehrere Plattformen hinweg funktionieren.
Das BarCode.Android-Paket bringt Barcodes Unterstützung für Android!
Lesen und Schreiben von BarCodes auf Android in .NET MAUI
- Laden Sie die C#-Bibliothek herunter, um Barcodes auf Android zu lesen und zu schreiben
- Erstellen Sie ein .NET MAUI App-Projekt
- Bearbeiten Sie die XAML-Datei, um eine Aktivierungsschaltfläche hinzuzufügen und Ausgabetext anzuzeigen
- Bearbeiten Sie die zugehörige C#-Datei, um die Barcode-Erkennung zu verarbeiten
- Laden Sie das Beispielprojekt für einen schnellen Einstieg herunter
IronBarcode Android Paket
Das BarCode.Android-Paket ermöglicht Barcode-Funktionen auf Android-Geräten über .NET-plattformübergreifende Projekte. Das Standard-BarCode-Paket ist nicht erforderlich.
Installation mit NuGet
Installieren-Paket BarCode.Android
Erstellen Sie ein .NET MAUI Projekt
Öffnen Sie Visual Studio und klicken Sie auf "Neues Projekt erstellen". Nach MAUI suchen, .NET MAUI App auswählen und auf 'Weiter' klicken.
Binden Sie die BarCode.Android Bibliothek ein
Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Die einfachste Methode ist die Verwendung von NuGet.
- Klicken Sie in Visual Studio mit der rechten Maustaste auf "Abhängigkeiten" und wählen Sie "NuGet-Pakete verwalten ...".
- Wählen Sie die Registerkarte "Durchsuchen" und suchen Sie nach "BarCode.Android".
- Wählen Sie das Paket "BarCode.Android" und klicken auf "Installieren".
Um Probleme mit anderen Plattformen zu vermeiden, ändern Sie die csproj-Datei, um das Paket nur dann einzubeziehen, wenn es auf der Android-Plattform ausgeführt wird. Um dies zu tun:
-
Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei Ihres Projekts und wählen Sie "Projektdatei bearbeiten".
-
Erstellen Sie ein neues ItemGroup-Element wie folgt:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> <PackageReference Include="BarCode.Android" Version="2025.3.4" /> </ItemGroup>XML -
Verschieben Sie den "BarCode.Android" PackageReference in die neu erstellte ItemGroup.
Die obigen Schritte verhindern, dass das "BarCode.Android" Paket auf Plattformen wie iOS verwendet wird. Zu diesem Zweck installieren Sie stattdessen BarCode.iOS.
Konfigurieren Sie das Android-Bundle
Damit Android funktioniert, müssen Sie die Einstellungen des Android-Bundles konfigurieren. Fügen Sie Ihrer ".csproj"-Datei den folgenden Eintrag hinzu, um die Konfigurationsdatei für das Android-Bundle anzugeben:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Erstellen Sie eine Datei namens "BundleConfig.json" im Stammverzeichnis des Projekts. Diese JSON-Datei enthält die erforderlichen Einstellungen für das Android-Bundle, die für die Funktionalität der Bibliothek entscheidend sind.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Diese Konfiguration stellt sicher, dass native Bibliotheken unkomprimiert sind, was ein notwendiger Schritt dafür ist, dass die Bibliothek in der Android-Umgebung ordnungsgemäß funktioniert.
Gestaltung der App-Oberfläche
Aktualisieren Sie die XAML-Datei, um Benutzern zu ermöglichen, Werte zur Erstellung von Barcodes und QR-Codes einzugeben. Zusätzlich fügen Sie einen Knopf hinzu, um ein Dokument zur Barcode-Erkennung auszuwählen. Hier ist ein Beispiel:
<?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>
Lesen und Schreiben von Barcodes
Aus dem oben gezeigten MainPage.xaml-Code sehen wir, dass das Kontrollkästchen bestimmt, ob der erzeugte Barcode und QR-Code im PDF-Format sein soll. Als Nächstes setzen wir den Lizenzschlüssel. Bitte verwenden Sie einen Test- oder bezahlten Lizenzschlüssel für diesen Schritt.
Der Code überprüft und ruft den Wert aus der barcodeInput-Variable ab und nutzt dann die CreateBarcode-Methode, um den Barcode zu erzeugen. Schließlich ruft er die SaveToDownloadsAsync-Methode auf, die die Datei sowohl für Android als auch für iOS geeignet speichert.
Auf iOS ist ein benutzerdefinierter Dateipfad erforderlich, um das Dokument in die Files-Anwendung zu exportieren.
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 NamespaceDas Projekt ausführen
Dies zeigt Ihnen, wie Sie das Projekt ausführen und die Barcode-Funktion nutzen können.
Laden Sie das .NET MAUI App-Projekt herunter
Sie können den vollständigen Code für diesen Leitfaden herunterladen. Er kommt als gezippte Datei, die Sie in Visual Studio als .NET MAUI App-Projekt öffnen können.
Klicken Sie hier, um das Projekt herunterzuladen.
Häufig gestellte Fragen
Was ist .NET MAUI und wie steht es im Zusammenhang mit der Barcode-Erfassung auf Android?
.NET MAUI, oder Multi-platform App UI, ist der Nachfolger von Xamarin.Forms und ermöglicht es Entwicklern, plattformübergreifende Anwendungen zu erstellen. Das BarCode.Android-Paket integriert sich mit .NET MAUI, um das Lesen und Schreiben von Barcodes auf Android-Geräten zu ermöglichen.
Wie füge ich die BarCode.Android-Bibliothek zu meinem .NET MAUI-Projekt hinzu?
Sie können die BarCode.Android-Bibliothek über NuGet in Visual Studio hinzufügen. Klicken Sie mit der rechten Maustaste auf 'Dependencies', wählen Sie 'Manage NuGet Packages', suchen Sie nach 'BarCode.Android' und klicken Sie auf 'Install'.
Kann das BarCode.Android-Paket für Plattformen außer Android verwendet werden?
Das BarCode.Android-Paket ist speziell für Android zugeschnitten. Für iOS müssen Sie stattdessen das BarCode.iOS-Paket verwenden.
Wie kann ich mein Projekt konfigurieren, um die BarCode.Android-Bibliothek nur für Android einzuschließen?
Sie sollten Ihre .csproj-Datei bearbeiten, um eine bedingte ItemGroup für das BarCode.Android-Paket nur bei Zielgeräten mit Android hinzuzufügen, wobei die TargetFramework-Bedingung verwendet wird.
Benötige ich eine spezielle Konfigurationsdatei, um die BarCode.Android-Bibliothek auf Android zu verwenden?
Ja, Sie müssen die Konfigurationsdatei für das Android-Bundle in Ihrer .csproj-Datei angeben, typischerweise 'BundleConfig.json' genannt, um sicherzustellen, dass native Bibliotheken nicht komprimiert sind.
Wie kann ich in einer MAUI-Anwendung mit IronBarcode einen Barcode erzeugen und speichern?
Sie können die BarcodeWriter-Klasse verwenden, um einen Barcode aus einer Texteingabe zu erstellen, das Format (PDF oder PNG) zu bestimmen und ihn dann mit einer Methode wie SaveToDownloadsAsync für Android und iOS zu speichern.
Welche Dateiformate werden für das Speichern erzeugter Barcodes in IronBarcode unterstützt?
IronBarcode ermöglicht das Speichern von Barcodes im PDF- oder PNG-Format, basierend auf der Wahl des Benutzers in der Anwendung.
Wie unterstützt IronBarcode das Verarbeiten von QR-Codes in einer .NET MAUI Android-App?
IronBarcode erleichtert die Erstellung und das Lesen von QR-Codes durch die QRCodeWriter-Klasse und ermöglicht Funktionen wie das Erzeugen von QR-Codes aus Eingabetext und das Lesen von Barcode-Daten aus Dateien.
Gibt es ein Beispielprojekt, um den Einstieg mit IronBarcode in .NET MAUI zu erleichtern?
Ja, Sie können ein vollständiges .NET MAUI App-Projekt mit dem im Leitfaden enthaltenen Beispielcode herunterladen, um einen schnellen Einstieg zu erhalten.
Welche Funktionen bietet IronBarcode zum Lesen von Barcodedaten aus Dateien?
IronBarcode kann Barcodes aus Bild- und PDF-Dateien mit der BarcodeReader-Klasse lesen, wobei die Ergebnisse entsprechend in der Anwendung formatiert und angezeigt werden.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.