Android'de .NET MAUI'de Barkod Okuma ve Yazma
.NET MAUI (Çoklu platform Uygulama Arayüzü), Xamarin.Forms'un halefidir ve geliştiricilere Android, iOS, macOS ve Windows için çapraz platform uygulamaları oluşturma imkanı sunar. Farklı platformlarda kesintisiz çalışan yerel kullanıcı arayüzlerinin oluşturulmasını sağlayarak geliştirme sürecini hızlandırır.
Android için barkod desteği sağlayan BarCode.Android paketi!
Android'de .NET MAUI'de Barkod Okuma ve Yazma
- Android üzerinde barkod okumak ve yazmak için C# kütüphanesini indirin
- Bir .NET MAUI Uygulama projesi oluşturun
- Bir etkinleştirme düğmesi eklemek ve çıktı metnini görüntülemek için XAML dosyasını düzenleyin
- Barkod tanımayı işlemek için ilgili C# dosyasını düzenleyin
- Hızlı bir başlangıç için örnek projeyi indirin
IronBarcode Android Paketi
Android cihazlarda barkod özelliklerini etkinleştiren BarCode.Android paketi, .NET çapraz platform projeleri aracılığıyla çalışır. Vanilya BarCode paketi gerekli değildir.
NuGet ile yükleyin
Install-Package BarCode.Android
Bir .NET MAUI Projesi Oluşturun
Visual Studio'yu açın ve "Yeni proje oluştur"a tıklayın. MAUI arayın, .NET MAUI Uygulamasını seçin ve "İleri" tıklayın.
BarCode.Android Kütüphanesini Ekleyin
Kütüphane çeşitli şekillerde eklenebilir. Belki de en kolay yol NuGet kullanmaktır.
- Visual Studio içinde "Dependencies" üzerine sağ tıklayın ve "NuGet Paketlerini Yönet..." seçeneğini seçin.
- "Gözat" sekmesini seçin ve "BarCode.Android" arayın.
- "BarCode.Android" paketini seçin ve "Yükle"ye tıklayın.
Diğer platformlarla sorun yaşamamak için csproj dosyanızı yalnızca Android platformunu hedefleyerek paketi dahil edecek şekilde değiştirin. Bunu yapmak için:
-
Projenizin *.csproj dosyası üzerine sağ tıklayın ve "Proje Dosyasını Düzenle" seçeneğini seçin.
-
Yeni bir ItemGroup elementi oluşturun:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> <PackageReference Include="BarCode.Android" Version="2025.3.4" /> </ItemGroup>XML -
"BarCode.Android" PackageReference öğesini yeni oluşturduğumuz ItemGroup içine taşıyın.
Yukarıdaki adımlar, "BarCode.Android" paketinin iOS gibi platformlarda kullanılmasını önleyecektir. Bu amaçla, bunun yerine BarCode.iOS yükleyin.
Android Paketi Yapılandırın
Android'in çalışması için Android paket ayarlarını yapılandırmanız gerekiyor. Projenizin ".csproj" dosyasına Android paket yapılandırma dosyasını belirtmek için şu girişi ekleyin:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Projede ana dizinde "BundleConfig.json" adında bir dosya oluşturun. Bu JSON dosyası, kütüphanenin işlevselliği için kritik olan Android paketinin gerekli ayarlarını içerir.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Bu yapılandırma, yerel kütüphanelerin sıkıştırılmamış olduğundan emin olur, bu, kütüphanenin Android ortamında düzgün şekilde çalışması için gerekli bir adımdır.
Uygulama Arayüzünü Tasarlayın
Kullanıcılara barkod ve QR kodları üretmek için değerler girebileceği bir XAML dosyasını güncelleyin. Ayrıca bir belge seçmek için bir buton ekleyin. İşte bir örnek:
<?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>
Barkodları Okuyun ve Yazın
MainPage.xaml kodundan, üretilen barkod ve QR kodunun PDF formatında olup olmayacağını belirlemek için onay kutusunun karar verdiğini görebiliriz. Sonraki adım olarak lisans anahtarını ayarlayın. Bu adım için lütfen deneme ya da ücretli bir lisans anahtarı kullanın.
Kod, önce barcodeInput değişkeninden değeri kontrol eder ve alır, ardından barkod oluşturmak için CreateBarcode yöntemini kullanır. Son olarak, bu dosyayı hem Android hem de iOS için uygun şekilde kaydeden SaveToDownloadsAsync yöntemini çağırır.
iOS üzerinde, belgeyi Files uygulamasına aktarmak için özel bir dosya yolu gereklidir.
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 NamespaceProjeyi Çalıştırın
Bu, projenin nasıl çalıştırılacağını ve barkod özelliğinin nasıl kullanılacağını gösterecektir.
.NET MAUI Uygulama Projesi İndirin
Bu kılavuzun tüm kodunu indirebilirsiniz. Visual Studio'da .NET MAUI Uygulama projesi olarak açabileceğiniz sıkıştırılmış bir dosya olarak gelir.
Projeyi indirmek için buraya tıklayın.
Sıkça Sorulan Sorular
.NET MAUI nedir ve Android'de barkod tarama ile nasıl ilişkili?
.NET MAUI veya Çok Platformlu Uygulama UI (Multi-platform App UI), Xamarin.Forms'un halefi olup geliştiricilerin çapraz platform uygulamaları oluşturmasına olanak tanır. BarCode.Android paketi, Android cihazlarda barkod okuma ve yazmayı etkinleştirmek için .NET MAUI ile entegre olur.
BarCode.Android kütüphanesini .NET MAUI projemi nasıl eklerim?
Visual Studio'da NuGet kullanarak BarCode.Android kütüphanesini ekleyebilirsiniz. 'Bağımlılıklar' üzerine sağ tıklayın, 'NuGet Paketlerini Yönet' seçeneğini seçin, 'BarCode.Android' arayın ve 'Yükle'ye tıklayın.
BarCode.Android paketi Android dışındaki platformlar için kullanılabilir mi?
BarCode.Android paketi özellikle Android için uyarlanmıştır. iOS için BarCode.iOS paketini kullanmanız gerekir.
Projemi sadece Android için BarCode.Android kütüphanesini içerecek şekilde nasıl yapılandırabilirim?
.csproj dosyanızı, Android hedeflenirken BarCode.Android paketi için koşullu bir ItemGroup ekleyerek düzenlemelisiniz, TargetFramework koşulunu kullanarak.
Android'de BarCode.Android kütüphanesini kullanmak için belirli bir yapılandırma dosyasına ihtiyacım var mı?
Evet, yerel kütüphanelerin sıkıştırılmadığından emin olmak için, Android paketi için genellikle 'BundleConfig.json' adında .csproj dosyanızda yapılandırma dosyasını belirtmeniz gerekir.
IronBarcode kullanarak MAUI uygulamasında barkod nasıl üretebilir ve kaydedebilirim?
BarcodeWriter sınıfını kullanarak metin girişinden bir barkod oluşturabilir, formatını (PDF veya PNG) belirleyebilir ve ardından Android ve iOS için SaveToDownloadsAsync gibi bir yöntemle kaydedebilirsiniz.
IronBarcode'da üretilen barkodların kaydedileceği dosya formatları nelerdir?
IronBarcode, kullanıcıların uygulamada tercihine bağlı olarak barkodların PDF veya PNG formatlarında kaydedilmesine olanak tanır.
IronBarcode, bir .NET MAUI Android uygulamasında QR kodlarını işlemeye nasıl yardımcı olur?
IronBarcode, QRCodeWriter sınıfı aracılığıyla QR kod oluşturma ve okuma işlemlerini kolaylaştırır, giriş metninden QR kodu oluşturma ve dosyalardan barkod verilerini okuma gibi işlevsellikler sağlar.
IronBarcode ile .NET MAUI'e başlamak için bir örnek proje mevcut mu?
Evet, hızlı bir başlangıç yapmak için kılavuzda verilen örnek kodla birlikte tam bir .NET MAUI Uygulama projesini indirebilirsiniz.
IronBarcode, dosyalardan barkod verilerini okuma konusunda hangi işlevleri sağlar?
IronBarcode, BarcodeReader sınıfını kullanarak görüntü ve PDF dosyalarından barkod okuyabilir, sonuçları uygun formatta uygulamada gösterir.
Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.