解决 react native android 出现 java.lang.ClassCastException: okhttp3.internal.http.RealResponseBody cannot be cast to com.RNFetchBlob.Response.RNFetchBlobFileResp
今天发现下载功能突然崩了,导致 APP 直接闪退有点严重呀,使用 Android Studio Logcat 打印出如下错误
18516-18761/com.example E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example, PID: 18516
java.lang.ClassCastException: okhttp3.internal.http.RealResponseBody cannot be cast to com.RNFetchBlob.Response.RNFetchBlobFileResp
at com.RNFetchBlob.RNFetchBlobReq.done(RNFetchBlobReq.java:594)
at com.RNFetchBlob.RNFetchBlobReq.access$100(RNFetchBlobReq.java:72)
at com.RNFetchBlob.RNFetchBlobReq$3.onResponse(RNFetchBlobReq.java:493)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:206)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
18516-18761/com.example I/Process: Sending signal. PID: 18516 SIG: 9
由于我用的是刚升级的 MIUI 12 所以我觉得发生这个错误的原因应该和 Android 10 的文件访问策略有关。因此,我通过将android:requestLegacyExternalStorage="true"
属性添加到AndroidManifest.xml 文件中的应用程序标签来临时修复,如下所示:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.android.example">
...
<application
android:name="com.android.example.MainApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:theme="@style/AppTheme">
...
</application>
</manifest>
虽然通过这方法能够暂时修复,但是有空的话还是尽快做一下 Android 10 的文件策略适配吧
Android 官方适配文档:https://developer.android.com/training/data-storage/use-cases