# Best Practices

Recommended best practices for Socket Mobile CaptureSDK integration to optimize the end-user experience. Covers monitoring scanner battery levels to prevent downtime during operations, configuring power state change notifications to alert users when a scanner needs charging, and ensuring reliable scanner connectivity. Includes code samples for reading battery level and setting up battery change notifications.

We recommend to use our CaptureSDK so the End Users can use our scanners and readers at their best and providing the best User Experience for them.

For instance, it is important to know the power state of the scanner as it is for the host to make sure it does not need to be recharged during the time the scanner is needed and the operation has a chance to change batteries or charge the scanner.

The application can check the battery level of the scanner using CaptureSDK. Additionally, many Socket Mobile scanners support battery level change notification.

Following are some examples on how to configure the scanner for these features.

## Reading the Battery Level

Here is example code showing how to request the scanner battery level information:

## Java

```java
void getBatteryLevel(DeviceClient device) {
    device.getBatteryLevel(new PropertyCallback() {
        @Override
        public void onComplete(CaptureError error, Property property) {
            if (error != null) {
                Log.e(TAG, "Get battery level failed: " + error.getMessage());
                return;
            }
            Log.d(TAG, "Battery level: " + property.getInt() + "%");
        }
    });
}
```

## Kotlin

```kotlin
fun getBatteryLevel(device: DeviceClient) {
    device.getBatteryLevel(PropertyCallback { error, property ->
        if (error != null) {
            Log.e(TAG, "Get battery level failed: ${error.message}")
            return@PropertyCallback
        }
        val level = property?.int ?: return@PropertyCallback
        Log.d(TAG, "Battery level: $level%")
    })
}
```

## Swift

```swift
device.getBatteryLevelWithCompletionHandler({ result, batteryLevel in
    if let batteryLevel = batteryLevel {
        let finalBatteryLevel = SKTHelper.getCurrentLevel(fromBatteryLevel: Int(batteryLevel))
        print("Get Battery Level: \(finalBatteryLevel) - Result: \(result.rawValue)")
    }
})
```

## C#

```csharp
// ask for the Battery Level
CaptureHelperDevice.BatteryLevelResult resultBattery = await device.GetBatteryLevelAsync();
Console.WriteLine($"Battery Level: {resultBattery.Percentage}");
```

## Dart

```dart
// getBatteryLevel() already returns a percentage (0-100)
final int batteryLevel = await device.getBatteryLevel();
debugPrint('Battery level: $batteryLevel%');

// Compare with the PowerState constants (onBattery, onCradle, onAc, unknown)
final int powerState = await device.getPowerState();
debugPrint('On battery: ${powerState == PowerState.onBattery}');
```

## JavaScript

```javascript
// Battery level is returned directly as a percentage (0-100)
const level = await device.getBatteryLevel();
console.log(`Battery level: ${level}%`);

// Power state
const power = await device.getPowerState();
console.log(`Power state: ${power}`);
```

## Get Battery Level Change and Power State Notifications

In order to receive the battery level change and power state notifications, you need to subscribe to the [device power events](/docs/using-capturesdk/capture-helper#device-power)

## Java

```java
// Battery level changes are delivered to EventBus subscribers as BatteryLevelEvent.
@Subscribe(threadMode = ThreadMode.MAIN)
public void onBatteryLevelChanged(BatteryLevelEvent event) {
    Log.d(TAG, "Battery level changed: " + event.getLevel() + "%");
}

// Power state changes are delivered to EventBus subscribers as PowerStateEvent.
@Subscribe(threadMode = ThreadMode.MAIN)
public void onPowerStateChanged(PowerStateEvent event) {
    Log.d(TAG, "Power state changed: " + PowerState.getString(event.getPowerState()));
}
```

## Kotlin

```kotlin
// Battery level changes are delivered to EventBus subscribers as BatteryLevelEvent.
@Subscribe(threadMode = ThreadMode.MAIN)
fun onBatteryLevelChanged(event: BatteryLevelEvent) {
    Log.d(TAG, "Battery level changed: ${event.level}%")
}

// Power state changes are delivered to EventBus subscribers as PowerStateEvent.
@Subscribe(threadMode = ThreadMode.MAIN)
fun onPowerStateChanged(event: PowerStateEvent) {
    Log.d(TAG, "Power state changed: ${PowerState.getString(event.powerState)}")
}
```

## Swift

```swift
import UIKit
import CaptureSDK

extension MyViewController: CaptureHelperDevicePowerDelegate {

    // MARK: - CaptureHelperDevicePowerDelegate

    func didChangeBatteryLevel(_ batteryLevel: Int, forDevice device: CaptureHelperDevice) {
        print("Battery level did change: \(SKTHelper.getCurrentLevel(fromBatteryLevel: batteryLevel))% for device \(device.deviceInfo.name ?? "")")
    }

    func didChangePowerState(_ powerState: SKTCapturePowerState, forDevice device: CaptureHelperDevice) {
        print("Receive a power state change \(powerState.rawValue) for device \(device.deviceInfo.name ?? "")")
    }

}
```

## C#

```csharp
// initialize CaptureHelper and subscribe to the events
capture = new CaptureHelper();
capture.ContextForEvents = SynchronizationContext.Current;
capture.DeviceBatteryLevel += OnDeviceBatteryLevel;
capture.DevicePowerState += OnDevicePowerState;
await capture.OpenAsync(appId, developerId, appKey);

// Battery Level change handler
void OnDeviceBatteryLevel(object? sender, CaptureHelper.BatteryLevelArgs e)
{
    string deviceName = e.CaptureDevice.GetDeviceInfo().Name;
    string percentage = CaptureHelper.ConvertBatteryLevelInPercentage(e.MinLevel, e.MaxLevel, e.CurrentLevel);
    Console.WriteLine($"Device: {deviceName}, Battery Level: {percentage}");
}

// Power State change handler
void OnDevicePowerState(object? sender, CaptureHelper.PowerStateArgs e)
{
    string deviceName = e.CaptureDevice.GetDeviceInfo().Name;
    Console.WriteLine($"Device: {deviceName}, Power State: {e.State}");
}
```

## Dart

```dart
await helper.open(
  appInfo,

  // The level is already converted to a percentage (0-100)
  onBatteryLevel: (int percent, CaptureHelperDevice device) {
    debugPrint('Battery level for ${device.name}: $percent%');
  },
  onPowerState: (int state, CaptureHelperDevice device) {
    debugPrint('Power state for ${device.name}: $state');
  },
);
```

## JavaScript

```javascript
import { CaptureHelper } from 'react-native-capture';

const capture = new CaptureHelper({
  appInfo,

  // Unlike getBatteryLevel(), the callback receives the raw packed value: the percentage is in the second byte
  onBatteryLevel: (level, device) => {
    console.log(`Battery level for ${device.name}: ${(level >> 8) & 0xff}%`);
  },
  onPowerState: (state, device) => {
    console.log(`Power state for ${device.name}: ${state}`);
  },
});

await capture.open();
```