添加try catch后签名APK出现OkHttp Dispatcher崩溃问题求助
IllegalStateException: closed in Signed APK Hey there, let's break down why your signed APK is throwing that frustrating IllegalStateException: closed error from the OkHttp Dispatcher, while debug builds work perfectly fine. This is a super common issue tied to differences between debug and release build configurations—most likely ProGuard/R8 obfuscation messing with OkHttp's internal classes.
Here are the actionable steps to fix this:
Add OkHttp-specific ProGuard/R8 rules
The obfuscator is renaming OkHttp's core classes and methods, which breaks its internal logic (since OkHttp relies on specific class names and method signatures to function correctly). Add these rules to yourproguard-rules.profile:-keep class okhttp3.** { *; } -keep interface okhttp3.** { *; } -keep class okio.** { *; } -keep interface okio.** { *; } -keepattributes SignatureThe
Signatureattribute ensures generic type information stays intact, which OkHttp uses for some of its internal operations.Double-check your try-catch and resource management
Even though debug builds work, make sure you're not accidentally closing OkHttp resources (likeResponseorResponseBody) before they're fully used. Use Java's try-with-resources syntax to auto-manage resources safely and avoid premature closes:OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("your-api-endpoint") .build(); try (Response response = client.newCall(request).execute()) { // Process your response here—no need to manually close it if (!response.isSuccessful()) throw new IOException("Unexpected code: " + response); String responseBody = response.body().string(); // Use the responseBody as needed } catch (IOException e) { e.printStackTrace(); // Handle the error appropriately }This syntax guarantees resources are closed only after you're done working with them, eliminating the risk of "closed" exceptions from manual mismanagement.
Verify consistent OkHttp versions across build variants
Rarely, debug and release builds might pull in different versions of OkHttp. Check yourbuild.gradlefile to ensure the same OkHttp version is used for all build variants:dependencies { implementation("com.squareup.okhttp3:okhttp:4.11.0") // Replace with your actual version }
Why this happens in signed APKs but not debug builds:
Debug builds usually disable obfuscation (minifyEnabled false) by default, so OkHttp's classes remain untouched. When you build a signed release APK, obfuscation kicks in—and without proper rules, it mangles OkHttp's internal structure. This leads to the closed exception when the Dispatcher tries to access obfuscated classes or methods that it expects to exist in their original form.
Start with the ProGuard rules first—that's almost certainly the root cause here. Let me know if you hit any snags!
内容的提问来源于stack exchange,提问作者dozieogbo

