Я хочу отправить и распечатать данные на устройство Bluetooth через TSPL для Android 13. На самом деле, эти части работают, но я хочу создать папку с именем LabelBasmaLogo в папке files в собственном каталоге приложения и распечатать logo.png изображение в нем, но что бы я ни делал, оно не сработало.
Думаю, это связано с разрешениями. Вы пробовали разные методы, но это не сработало
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using Android.Views;
using Android.Widget;
using AndroidX.AppCompat.App;
namespace Etiket_basma
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private EditText dateEntry;
private EditText weightEntry;
private Spinner printerPicker;
private Button printButton;
private Button uploadLogoButton;
private Android.Graphics.Bitmap logoBitmap;
private const int REQUEST_BLUETOOTH_PERMISSIONS = 1;
private const int REQUEST_IMAGE_PICK = 2;
private string logoFolderPath;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
InitializeUIComponents();
RequestPermissions();
dateEntry.Text = DateTime.Today.ToString("dd/MM/yyyy");
dateEntry.Click += DateEntry_Click;
LoadPairedPrinters();
printButton.Click += PrintButton_Click;
}
private void InitializeUIComponents()
{
dateEntry = FindViewById(Resource.Id.dateEntry);
weightEntry = FindViewById(Resource.Id.weightEntry);
printerPicker = FindViewById(Resource.Id.printerPicker);
printButton = FindViewById(Resource.Id.printButton);
uploadLogoButton = FindViewById(Resource.Id.selectImageButton);
}
private void RequestPermissions()
{
if (CheckSelfPermission(Android.Manifest.Permission.Bluetooth) != (int)Permission.Granted ||
CheckSelfPermission(Android.Manifest.Permission.BluetoothAdmin) != (int)Permission.Granted ||
CheckSelfPermission(Android.Manifest.Permission.BluetoothConnect) != (int)Permission.Granted ||
CheckSelfPermission(Android.Manifest.Permission.AccessFineLocation) != (int)Permission.Granted ||
CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted ||
CheckSelfPermission(Android.Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
RequestPermissions(new string[] {
Android.Manifest.Permission.Bluetooth,
Android.Manifest.Permission.BluetoothAdmin,
Android.Manifest.Permission.AccessFineLocation,
Android.Manifest.Permission.BluetoothConnect,
Android.Manifest.Permission.WriteExternalStorage,
Android.Manifest.Permission.ReadExternalStorage
}, REQUEST_BLUETOOTH_PERMISSIONS);
}
}
private void LoadPairedPrinters()
{
List printers = GetPairedPrinters();
ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, printers);
printerPicker.Adapter = adapter;
}
private void DateEntry_Click(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, today.Year, today.Month - 1, today.Day);
dialog.Show();
}
private void OnDateSet(object sender, DatePickerDialog.DateSetEventArgs e)
{
dateEntry.Text = e.Date.ToString("dd/MM/yyyy");
}
private List GetPairedPrinters()
{
List printerList = new List();
BluetoothManager bluetoothManager = (BluetoothManager)GetSystemService(BluetoothService);
BluetoothAdapter bluetoothAdapter = bluetoothManager.Adapter;
if (bluetoothAdapter == null)
{
ShowToast("Bluetooth desteği yok!");
return printerList;
}
foreach (var device in bluetoothAdapter.BondedDevices)
{
printerList.Add(device.Name);
}
return printerList;
}
private async void PrintButton_Click(object sender, EventArgs e)
{
string selectedPrinter = printerPicker.SelectedItem?.ToString();
string date = dateEntry.Text;
string weight = weightEntry.Text;
if (string.IsNullOrWhiteSpace(date) || string.IsNullOrWhiteSpace(weight))
{
ShowToast("Lütfen Tarih ve Kilo girin!");
return;
}
await PrintToBluetoothAsync(selectedPrinter, date, weight);
}
private async Task PrintToBluetoothAsync(string printerName, string date, string weight)
{
string address = GetPrinterAddress(printerName);
if (string.IsNullOrEmpty(address))
{
ShowToast("Yazıcı adresi bulunamadı!");
return;
}
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
BluetoothDevice device = bluetoothAdapter.GetRemoteDevice(address);
BluetoothSocket socket = null;
try
{
socket = device.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
await Task.Run(() => socket.Connect());
string tsplData = GenerateTsplData(date, weight);
byte[] logoData = logoBitmap != null ? ConvertBitmapToTspl(logoBitmap) : null;
using (var outputStream = socket.OutputStream)
{
await outputStream.WriteAsync(Encoding.ASCII.GetBytes(tsplData), 0, tsplData.Length);
if (logoData != null)
{
await outputStream.WriteAsync(logoData, 0, logoData.Length);
}
await outputStream.WriteAsync(new byte[] { 0x0A }, 0, 1); // Satır atla
}
ShowToast("Yazdırma işlemi başarılı!");
}
catch (Exception ex)
{
ShowToast($"Yazdırma işlemi başarısız: {ex.Message}");
}
finally
{
socket?.Close();
}
}
private string GenerateTsplData(string date, string weight)
{
return $"SIZE 72 mm, 38 mm\n" + // Etiket boyutu: 72mm genişlik, 38mm yükseklik
$"GAP 2 mm, 0 mm\n" + // Etiketler arasındaki boşluk
$"DENSITY 7\n" + // Yazıcı yoğunluğu
$"SET TEAR ON\n" + // Yırtma fonksiyonunu aç
$"CLS\n" + // Temizle
$"TEXT 01,60,\"40\",0,1,1,\"AYRO BILISIM HIZMETLERI\"\n" + // Şirket bilgisi
$"TEXT 01,120,\"58\",0,1,1,\"TARIH:{date}\"\n" + // Tarih
$"TEXT 01,190,\"50\",0,1,1,\"KILO:{weight} KG\"\n" + // Kilo
$"PRINT 1,1\n"; // Baskı
}
private string GetPrinterAddress(string printerName)
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
if (bluetoothAdapter == null)
{
ShowToast("Bluetooth desteği yok!");
return null;
}
foreach (BluetoothDevice device in bluetoothAdapter.BondedDevices)
{
if (device.Name == printerName)
{
return device.Address; // Eşleşen yazıcının adresini döndür
}
}
return null;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_PICK && resultCode == Result.Ok)
{
var uri = data.Data;
logoBitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
string logoPath = System.IO.Path.Combine(FilesDir.AbsolutePath, "EtiketBasmaLogolar", "logo.png");
using (var stream = new FileStream(logoPath, FileMode.Create))
{
logoBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
}
ShowToast("Logo yüklendi!");
}
}
private byte[] ConvertBitmapToTspl(Android.Graphics.Bitmap bitmap)
{
// Bitmap'i siyah beyaz formata dönüştür
Android.Graphics.Bitmap monochromeBitmap = ConvertToMonochrome(bitmap);
using (MemoryStream stream = new MemoryStream())
{
monochromeBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
byte[] imageBytes = stream.ToArray(); // Burada imageBytes tanımlanıyor
// TSPL komutları
StringBuilder tsplData = new StringBuilder();
tsplData.AppendLine($"BITMAP 0,0,{monochromeBitmap.Width},{monochromeBitmap.Height},1,{imageBytes.Length},0,0,0");
// Bitmap'i ikili veriye dönüştürme
foreach (byte b in imageBytes)
{
tsplData.Append(b.ToString("X2")); // Her baytı hexadecimal formatta ekle
}
return Encoding.ASCII.GetBytes(tsplData.ToString());
}
}
private Android.Graphics.Bitmap ConvertToMonochrome(Android.Graphics.Bitmap original)
{
// Yeni monokrom bitmap oluştur
Android.Graphics.Bitmap monochromeBitmap = Android.Graphics.Bitmap.CreateBitmap(original.Width, original.Height, Android.Graphics.Bitmap.Config.Argb8888);
for (int y = 0; y < original.Height; y++)
{
for (int x = 0; x < original.Width; x++)
{
// Orijinal pikseldan renk bilgisini al
int pixel = original.GetPixel(x, y);
// Pikselin gri tonunu hesapla
int gray = (int)(0.299 * Android.Graphics.Color.GetRedComponent(pixel) +
0.587 * Android.Graphics.Color.GetGreenComponent(pixel) +
0.114 * Android.Graphics.Color.GetBlueComponent(pixel));
// Monokrom pikseli ayarla
monochromeBitmap.SetPixel(x, y, Android.Graphics.Color.Argb(255, gray, gray, gray));
}
}
return monochromeBitmap;
}
private void ShowToast(string message)
{
Toast.MakeText(this, message, ToastLength.Short).Show();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... in-any-way
Никак не смог распечатать logo.png ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение