Jak czytac i pisac kody kreskowe na Androidzie w .NET MAUI
.NET MAUI (Multi-platform App UI) jest nastepca Xamarin.Forms, umożliwiajacym deweloperom budowe aplikacji wielopłatformowych na Androida, iOS, macOS i Windows z użyciem .NET. Usprawnia proces tworzenia poprzez umożliwienie tworzenia natywnych interfejsow użytkownika, ktore działaja bezproblemowo na wielu platformach.
Pakiet BarCode.Android zapewnia obsługę BARCODE w systemie Android!
Jak czytac i pisac kody kreskowe na Androidzie w .NET MAUI
Pakiet IronBarcode dla Androida
Pakiet BarCode.Android umożliwia korzystanie z funkcji BARCODE na urządzeniach z systemem Android za pośrednictwem wieloplatformowych projektów .NET. Standardowy pakiet BarCode nie jest potrzebny.
Install-Package BarCode.Android
Zainstaluj za pomocą NuGet
Install-Package BarCode.Android
Utworz projekt .NET MAUI
Otworz Visual Studio i kliknij na "Utworz nowy projekt". Wyszukaj MAUI, wybierz .NET MAUI App i "Dalej".
Dodaj biblioteke BarCode.Android
Biblioteke można dodac na różne sposoby. Najłatwiej jest uzyc NuGet.
- W Visual Studio, kliknij prawym przyciskiem myszy na "Dependencies" i wybierz "Manage NuGet Packages ...".
- Wybierz zakladke "Browse" i wyszukaj "BarCode.Android".
- Wybierz pakiet "BarCode.Android" i kliknij "Instaluj".
Aby uniknąć problemow z innymi platformami, zmodyfikuj plik csproj, aby uwzględnić pakiet tylko przy celowaniu w platforme Android. Aby to zrobic:
- Kliknij prawym przyciskiem na plik *.csproj w swoim projekcie i wybierz "Edit Project File".
- Utworz nowy element ItemGroup, jak poniżej:
<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>
- Przenies PackageReference dla "BarCode.Android" do ItemGroup, ktory wlasnie utworzylismy.
Powyzej opisane kroki zapobiegna użyciu pakietu "BarCode.Android" na platformach takich jak iOS. W tym celu, zainstaluj BarCode.iOS zamiast tego.
Skonfiguruj pakiet Androida
Aby Android działal, należy skonfigurować ustawienia pakietu Android. W swoim pliku ".csproj" dodaj następujący wpis, aby okreslic plik konfiguracyjny dla pakietu Android:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Utworz plik o nazwie "BundleConfig.json" w katalogu głównym projektu. Ten plik JSON zawiera wymagane ustawienia dla pakietu Android, ktore sa kluczowe dla działania biblioteki.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Ta konfiguracja zapewnia, ze natywne biblioteki sa nierozerwiate, co jest koniecznym krokiem dla poprawnego funkcjonowania biblioteki w środowisku Android.
Zaprojektuj interfejs aplikacji
Zaktualizuj plik XAML, aby umożliwic użytkownikom wprowadzanie wartosci do generowania kodow kreskowych i kodow QR. Dodatkowo, dodaj przycisk do wyboru dokumentu do odczytu kodow kreskowych. Oto przykład:
<?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>
Czytaj i pisz kody kreskowe
Na podstawie kodu MainPage.xaml powyzej widzimy, ze checkbox decyduje, czy wygenerowany kod kreskowy i kod QR powinien być w formacie PDF. Nastepne ustawiamy klucz licencyjny. Uzyj prosze klucza licencyjnego proef lub platnego dla tego kroku.
Kod sprawdza i pobiera wartość ze zmiennej barcodeInput, a następnie używa metody CreateBarcode do wygenerowania BARCODE. Na koniec wywołuje metodę SaveToDownloadsAsync, która zapisuje plik w sposób odpowiedni zarówno dla systemu Android, jak i iOS.
W systemie iOS wymagana jest niestandardowa ścieżka pliku, aby wyeksportować dokument do aplikacji 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);
}
}
}
}
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 Namespace
Uruchom projekt
To pokaze, jak uruchomic projekt i korzystać z funkcji kodu kreskowego.
Pobierz projekt aplikacji .NET MAUI
Możesz pobrać pełny kod do tego przewodnika. Jest dostępny jako spakowany plik, który możesz otworzyć w Visual Studio jako projekt .NET MAUI App.
Często Zadawane Pytania
Jak mogę tworzyć i skanować kody kreskowe w aplikacji .NET MAUI na Androidzie?
Możesz użyć pakietu BarCode.Android w ramach projektu .NET MAUI, aby tworzyć i skanować kody kreskowe na urządzeniach z Androidem. Obejmuje to skonfigurowanie pakietu za pomocą NuGet w Visual Studio i wdrażanie funkcjonalności kodów kreskowych za pomocą dostarczonych metod takich jak WriteBarcode i ReadBarcode.
Jakie kroki są konieczne, aby skonfigurować funkcjonalność kodów kreskowych dla Androida w projekcie .NET MAUI?
Aby skonfigurować funkcjonalność kodów kreskowych w projekcie .NET MAUI, zainstaluj pakiet BarCode.Android używając NuGet, skonfiguruj twój plik .csproj, aby uwzględniał pakiet dla Androida i upewnij się, że twoja paczka Androida jest skonfigurowana za pomocą pliku BundleConfig.json.
Jak skonfigurować plik .csproj, aby uwzględniał funkcjonalność kodów kreskowych tylko dla Androida?
Edytuj plik .csproj, dodając
Jaki jest cel używania pliku BundleConfig.json w projektach Android?
Plik BundleConfig.json jest używany do konfigurowania ustawień paczki Android, zapewniając, że natywne biblioteki są nieskompresowane. Jest to niezbędne, aby biblioteka kodów kreskowych działała poprawnie na urządzeniach z Androidem.
Jak mogę zaprojektować interfejs dla operacji na kodach kreskowych w aplikacji .NET MAUI?
Zaprojektuj interfejs aplikacji używając XAML, aby umożliwić użytkownikom wprowadzanie danych do generowania kodów kreskowych i QR. Uwzględnij przyciski do wyboru dokumentów do odczytu kodów kreskowych oraz do generowania, zapisywania i skanowania kodów kreskowych.
Jakie metody są używane w C# do generowania i odczytu kodów kreskowych w aplikacji?
W aplikacji .NET MAUI użyj takich metod jak WriteBarcode, WriteQRcode i ReadBarcode, aby generować kody kreskowe, tworzyć kody QR i odczytywać kody kreskowe z plików odpowiednio.
Jak mogę przetestować funkcje kodów kreskowych w mojej aplikacji .NET MAUI?
Po skonfigurowaniu projektu z niezbędnymi ustawieniami i implementacjami kodu kreskowego, możesz przetestować funkcje, uruchamiając projekt na urządzeniu lub emulatorze Android za pośrednictwem Visual Studio.
Gdzie mogę znaleźć kompletny projekt aplikacji .NET MAUI z funkcjonalnościami kodów kreskowych?
Kompletny projekt aplikacji .NET MAUI z funkcjonalnościami kodów kreskowych można pobrać w formacie zip z witryny IronBarcode. Ten projekt można otworzyć w Visual Studio do dalszej eksploracji i dostosowywania.
Czy potrzebna jest licencja do używania biblioteki kodów kreskowych w moim projekcie na Androidzie?
Tak, użycie biblioteki kodów kreskowych w swoim projekcie wymaga klucza licencyjnego wersji próbnej lub płatnej. Musisz wprowadzić ten klucz w konstruktorze MainPage, aby aktywować funkcje biblioteki.
Czy IronBarcode obsługuje przetwarzanie partii kodów kreskowych?
Tak, IronBarcode wspiera przetwarzanie wsadowe, umożliwiając programistom generowanie lub odczytywanie wielu kodów kreskowych w jednej operacji, zwiększając efektywność dużych aplikacji.

