Skip to main content

B. Handling Background Tasks

The Entrupy Android SDK may perform network operations, such as uploading images, that can continue even if the application is sent to the background. To ensure these tasks complete successfully and the SDK can process their results, it's important to correctly handle background processing in your Android application.

1. Background Processing Considerations

Android handles background processing differently than iOS. The Entrupy Android SDK is designed to work with Android's background processing mechanisms:

  • WorkManager Integration: The SDK may use WorkManager for reliable background processing of uploads and downloads.
  • Foreground Services: For long-running operations, the SDK may use foreground services to ensure tasks complete.
  • Network State Handling: The SDK handles network connectivity changes and retries operations when connectivity is restored.

2. Application Lifecycle Handling

Activity Lifecycle

The SDK automatically handles activity lifecycle events, but you should ensure proper integration:

// Kotlin
class YourActivity : AppCompatActivity(), EntrupyCaptureCallback {

override fun onPause() {
super.onPause()
// The SDK will continue background operations
// No special handling required for most cases
}

override fun onResume() {
super.onResume()
// The SDK will automatically check for completed background operations
// and trigger appropriate callbacks
}

override fun onDestroy() {
super.onDestroy()
// Clean up any SDK resources if needed
// The SDK handles its own cleanup
}
}

Application Class Integration

For global background task handling, you can integrate with your Application class:

// Kotlin
class YourApplication : Application() {

override fun onCreate() {
super.onCreate()

// Initialize the SDK
EntrupySDK.initialize(this, "your_api_key")

// Register for network state changes if needed
registerNetworkCallback()
}

private fun registerNetworkCallback() {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
// Network is available, SDK will automatically retry failed operations
println("Network available - SDK will retry operations if needed")
}

override fun onLost(network: Network) {
// Network is lost, SDK will queue operations for retry
println("Network lost - SDK will queue operations")
}
}

connectivityManager.registerDefaultNetworkCallback(networkCallback)
}
}

3. Background Upload Handling

Automatic Background Processing

The SDK automatically handles background uploads:

// Kotlin
// When starting a capture, the SDK handles background processing automatically
EntrupySDK.getInstance().startCapture(
context = this,
itemMetadata = metadata,
captureCallback = object : EntrupyCaptureCallback {
override fun onCaptureCompleteSuccessfully(result: EntrupyCaptureResult, item: Map<String, Any>) {
// This callback will be triggered even if the app was backgrounded during upload
println("Capture completed successfully: ${result.item.entrupyId}")
}

override fun onCaptureFailWithError(errorCode: EntrupyErrorCode, description: String, localizedDescription: String, item: Map<String, Any>) {
// Handle errors, including network-related errors
when (errorCode) {
EntrupyErrorCode.NETWORK_ERROR -> {
// SDK will automatically retry when network is available
println("Network error - SDK will retry automatically")
}
else -> {
// Handle other errors
println("Capture failed: $localizedDescription")
}
}
}
}
)

Manual Background Task Management

If you need to manually manage background tasks, you can use WorkManager:

// Kotlin
// Example of manual background task management (if needed)
class EntrupyBackgroundWorker(
context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {

override suspend fun doWork(): Result {
return try {
// Perform background work
// The SDK handles its own background processing
// This is just an example of how you might handle other background tasks

Result.success()
} catch (e: Exception) {
Result.retry()
}
}
}

// Schedule background work if needed
val backgroundWork = OneTimeWorkRequestBuilder<EntrupyBackgroundWorker>()
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1000, TimeUnit.MILLISECONDS)
.build()

WorkManager.getInstance(applicationContext)
.enqueueUniqueWork("entrupy_background_work", ExistingWorkPolicy.REPLACE, backgroundWork)

4. Battery Optimization Considerations

Requesting Battery Optimization Exemption

For critical operations, you may want to request exemption from battery optimization:

// Kotlin
class YourActivity : AppCompatActivity() {

private fun requestBatteryOptimizationExemption() {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val packageName = packageName
if (!powerManager.isIgnoringBatteryOptimizations(packageName)) {
val intent = Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
data = Uri.parse("package:$packageName")
}
startActivity(intent)
}
}
}
}

Handling Doze Mode

The SDK is designed to work with Android's Doze mode and App Standby:

// Kotlin
// The SDK automatically handles Doze mode and App Standby
// No special configuration required for most use cases

5. Best Practices

1. Network Handling

  • Automatic Retry: The SDK automatically retries failed network operations when connectivity is restored.
  • Offline Queue: Operations are queued when offline and executed when connectivity returns.
  • Manual Retry: Provide users with manual retry options for critical operations.

2. User Experience

  • Progress Indicators: Show appropriate progress indicators for long-running operations.
  • Status Updates: Keep users informed about the status of background operations.
  • Error Handling: Provide clear error messages and recovery options.

3. Resource Management

  • Memory Usage: The SDK is optimized for minimal memory usage during background operations.
  • Battery Usage: Background operations are designed to minimize battery impact.
  • Storage: Temporary files are automatically cleaned up after operations complete.

6. Troubleshooting

Common Issues

  1. Uploads Not Completing

    • Check network connectivity
    • Verify battery optimization settings
    • Ensure the app has necessary permissions
  2. Callbacks Not Triggered

    • Verify callback registration
    • Check activity lifecycle handling
    • Ensure proper SDK initialization
  3. Background Processing Delays

    • Check device battery optimization settings
    • Verify WorkManager configuration
    • Monitor network connectivity

This setup ensures that the SDK can reliably manage its network activity, contributing to a more robust authentication experience for your users.