Android中如何关闭/释放AWSAppSyncClient以解决内存泄漏问题
First, let's break down the root cause from your stack trace: the leak stems from an unclosed CursorWindow originating in AppSync's offline mutation cache (AppSyncMutationSqlCacheOperations). Since you're using a singleton AWSAppSyncClient, these SQLite-related resources won't be released automatically unless you explicitly shut down the client.
Step 1: Understand the Closure Mechanism
The AWSAppSyncClient implements the AutoCloseable interface, which means you can call its close() method to clean up internal resources like database connections, cached cursors, and offline mutation managers—exactly what's needed to fix the StrictMode leak.
Step 2: Integrate Closure with Koin (Your Dependency Injection)
Since you're using Koin to manage the singleton instance, leverage Koin's onClose callback to ensure the client is properly disposed when the instance is no longer needed. Update your Koin module definition like this:
single(createdAtStart = false) { AWSAppSyncClient.builder() .context(get()) .awsConfiguration(get()) .credentialsProvider( CognitoCachingCredentialsProvider( get(), // Your existing Cognito config here ) ) .build() } onClose { client -> try { client.close() Log.d("AppSyncClient", "Successfully cleaned up AWSAppSyncClient resources") } catch (e: Exception) { Log.e("AppSyncClient", "Error closing AWSAppSyncClient", e) } }
Step 3: Trigger Closure at App Shutdown
To ensure the Koin singleton is disposed when your app exits, add a lifecycle listener to your application class:
class MyApplication : Application(), LifecycleObserver { override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver(this) // Initialize Koin here as usual } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onAppTerminated() { // Close all Koin-managed instances to trigger the AppSync client's onClose callback getKoin().closeAll() } }
Why This Fixes the Leak
Calling close() on AWSAppSyncClient triggers cleanup of:
- Offline mutation cache database connections
- Any open
Cursorinstances used by the SQL cache operations (the exact issue flagged in your StrictMode log) - Internal network and credential provider resources tied to the client
Key Notes
- Don't close the client during normal app navigation (e.g., in Fragment
onDestroy)—it's a singleton meant for reuse across your app. Only close it when the entire app is exiting. - If you weren't using Koin, store the singleton in your Application class and call
client.close()in theonTerminate()method (note:onTerminate()isn't guaranteed to run on all devices, but works for testing and most production scenarios).
内容的提问来源于stack exchange,提问作者M.SH

