Ich entwickle ein Kondensator -Plugin in Java für Druckbelege. Der gleiche Code funktioniert perfekt in einer nativen Android-App mit allen Druckern, aber wenn sie in einem Kondensator-Plugin verwendet werden, arbeiten einige Drucker, während andere versagen. Fehler: < /p>
Code: Select all
Connection failed: read failed, socket might be closed or timeout, read ret: -1
< /code>
Versucht mit BluetoothSocket direkt anstelle von Druckooth.Sending plugin error: {"save":true,"callbackId":"6990095","pluginId":"PrinterBridge","methodName":"print","success":false,"error":{"message":"Bluetooth connect permission not granted"}}
< /code>
verifiziert, dass die erforderlichen Bluetooth -Berechtigungen gewährt werden, aber das [url=viewtopic.php?t=15738]Problem[/url] bleibt bestehen. Plugin, während sie in einer nativen Android-App gut funktionieren.
@CapacitorPlugin(
name = "PrinterBridge",
permissions = {
@Permission(
alias = "bluetooth",
strings = {
// Basic Bluetooth permissions
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
// Android 12+ permissions
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
// Android 14+ permission
Manifest.permission.NEARBY_WIFI_DEVICES
}
)
}
)
public class MyPlugin extends Plugin {
private static final String TAG = "PrinterBridge";
private static final int BLUETOOTH_PERMISSION_REQUEST = 1001;
private BluetoothGatt bluetoothGatt;
private PluginCall savedPrintCall;
@PluginMethod
public void print(PluginCall call) {
Log.d(TAG, "Print method called");
// Store this call for later use
savedPrintCall = call;
call.setKeepAlive(true);
// First check if we have permission
if (!hasRequiredPermissions()) {
Log.d(TAG, "Bluetooth permissions not granted, requesting permissions");
// Use Capacitor's permission system properly
checkBluetoothPermissions(call);
return;
}
// If we already have permissions, proceed with printing
Log.d(TAG, "Permissions already granted, proceeding with print operation");
executePrintOperation(call);
}
@PermissionCallback
private void bluetoothPermissionsCallback(PluginCall call) {
Log.d(TAG, "Bluetooth permission callback received");
if (hasRequiredPermissions()) {
Log.d(TAG, "Bluetooth permissions now granted, proceeding with print");
if (savedPrintCall != null) {
executePrintOperation(savedPrintCall);
} else {
// Just resolve the current call
JSObject result = new JSObject();
result.put("permissionsGranted", true);
call.resolve(result);
}
} else {
Log.e(TAG, "Bluetooth permissions denied by user");
// Show dialog offering to open settings
Toast.makeText(getContext(), "Bluetooth permissions required for printing", Toast.LENGTH_LONG).show();
if (savedPrintCall != null) {
savedPrintCall.reject("Bluetooth permissions denied. Please grant permissions in Settings.");
savedPrintCall = null;
} else {
call.reject("Bluetooth permissions denied");
}
}
}
private void executePrintOperation(PluginCall call) {
new Thread(() -> {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice printer = null;
BluetoothSocket socket = null;
try {
if (bluetoothAdapter == null) {
finishWithError("Bluetooth not supported on this device");
return;
}
String deviceId = call.getString("deviceId");
if (deviceId == null) {
finishWithError("Device ID is required");
return;
}
Log.d(TAG, "Attempting to connect to device: " + deviceId);
printer = bluetoothAdapter.getRemoteDevice(deviceId);
if (printer == null) {
finishWithError("Printer not found with ID: " + deviceId);
return;
}
// Create socket with SPP UUID
UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
finishWithError("Bluetooth connect permission not granted");
return;
}
Log.d(TAG, "Attempting to create socket to " + printer.getName());
socket = printer.createRfcommSocketToServiceRecord(SPP_UUID);
// Cancel discovery as it slows down connection
bluetoothAdapter.cancelDiscovery();
// Connect with timeout
Log.d(TAG, "Connecting to printer socket...");
socket.connect();
if (socket.isConnected()) {
// Existing printing code...
Log.d(TAG, "Socket connected, sending data...");
// Rest of your printing logic...
// Close socket
socket.close();
finishWithSuccess("Print data sent successfully");
} else {
finishWithError("Failed to connect to printer socket");
}
} catch (Exception e) {
Log.e(TAG, "Direct print error: " + e.getMessage(), e);
finishWithError("Direct print error: " + e.getMessage());
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
Log.e(TAG, "Error closing socket: " + e.getMessage());
}
}
}).start();
}
public void checkBluetoothPermissions(PluginCall call) {
JSObject result = new JSObject();
result.put("androidVersion", Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
boolean connectGranted = ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED;
boolean scanGranted = ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED;
result.put("bluetoothConnect", connectGranted);
result.put("bluetoothScan", scanGranted);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
boolean nearbyDevices = ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.NEARBY_WIFI_DEVICES) == PackageManager.PERMISSION_GRANTED;
result.put("nearbyWifiDevices", nearbyDevices);
}
result.put("allPermissionsGranted", hasRequiredPermissions());
} else {
result.put("status", "Bluetooth permissions automatically granted for this Android version");
result.put("allPermissionsGranted", true);
}
call.resolve(result);
}
@PluginMethod
public void forceRequestPermissions(PluginCall call) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
String[] permissions;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
permissions = new String[] {
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.NEARBY_WIFI_DEVICES
};
} else {
permissions = new String[] {
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN
};
}
// Direct request that should show the permission dialog
ActivityCompat.requestPermissions(getActivity(), permissions, BLUETOOTH_PERMISSION_REQUEST);
// Resolve so we don't hang
JSObject result = new JSObject();
result.put("permissionDialogShown", true);
call.resolve(result);
} else {
JSObject result = new JSObject();
result.put("status", "No permissions needed for this Android version");
call.resolve(result);
}
}
@PluginMethod
public void openAppSettings(PluginCall call) {
try {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
getActivity().startActivity(intent);
call.resolve();
} catch (Exception e) {
call.reject("Could not open app settings: " + e.getMessage());
}
}
public boolean hasRequiredPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { // Android 14+
return ContextCompat.checkSelfPermission(
getContext(), Manifest.permission.BLUETOOTH_CONNECT
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
getContext(), Manifest.permission.BLUETOOTH_SCAN
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
getContext(), Manifest.permission.NEARBY_WIFI_DEVICES
) == PackageManager.PERMISSION_GRANTED;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12+
return ContextCompat.checkSelfPermission(
getContext(), Manifest.permission.BLUETOOTH_CONNECT
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
getContext(), Manifest.permission.BLUETOOTH_SCAN
) == PackageManager.PERMISSION_GRANTED;
}
return true; // Permissions automatically granted on Android < 12
}
private void finishWithSuccess(String message) {
// Run on UI thread to safely resolve the call
getActivity().runOnUiThread(() -> {
if (savedPrintCall != null) {
JSObject result = new JSObject();
result.put("success", true);
result.put("message", message);
savedPrintCall.resolve(result);
savedPrintCall = null;
}
});
}
private void finishWithError(String errorMessage) {
// Run on UI thread to safely reject the call
getActivity().runOnUiThread(() -> {
if (savedPrintCall != null) {
savedPrintCall.reject(errorMessage);
savedPrintCall = null;
}
});
}
@Override
protected void handleOnDestroy() {
// Clean up any pending calls when the plugin is destroyed
if (savedPrintCall != null) {
savedPrintCall.reject("Plugin was destroyed before printing completed");
savedPrintCall = null;
}
if (bluetoothGatt != null) {
if (ActivityCompat.checkSelfPermission(this.getContext(),
Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
bluetoothGatt.close();
}
bluetoothGatt = null;
}
super.handleOnDestroy();
}
}