如何通过Intent分享Firebase Storage的GIF?点击分享闪退怎么办
闪退原因及修复方案
核心崩溃原因
代码存在几处确定性错误,会直接触发崩溃:
- 资源ID获取方法参数错误:
getIdentifier("gm_gif_1.gif", null, null)的后两个参数不能传null,且raw目录下的资源名不能带.gif后缀,该方法会返回无效ID 0,调用openRawResource(0)会直接抛出资源不存在异常。而代码的catch块为空,异常被直接吞掉,GIF文件实际没有写入成功,后续FileProvider查找不存在的文件会直接抛出异常闪退。 - 没有配置FileProvider,也没有给分享目标应用授予文件读权限,即使文件写入成功也会触发崩溃。
- 输入输出流没有正确关闭,空异常捕获会隐藏所有写入错误,无法排查问题。
第一步:配置FileProvider
- 在
AndroidManifest.xml的<application>标签内添加FileProvider注册:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
如果项目仍在使用旧版support依赖而非AndroidX,将android:name替换为android.support.v4.content.FileProvider即可。
- 在
res/xml目录下新建file_paths.xml,添加外部缓存目录的访问配置:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-cache-path name="shared_gif" path="." /> </paths>
第二步:修正分享逻辑
使用try-with-resources自动关闭输入输出流,补全权限参数,修正资源获取逻辑。如果GIF实际从Firebase下载,只需要把代码中读取raw资源的输入流,替换为Firebase下载得到的输入流即可:
public void sharegif(){ File gifFile = new File(getExternalCacheDir(), "gm_gif_1.gif"); // 将GIF写入缓存文件,语法自动关闭流 try ( InputStream fis = getResources().openRawResource( getResources().getIdentifier("gm_gif_1", "raw", getPackageName()) ); FileOutputStream fos = new FileOutputStream(gifFile) ) { byte[] buffer = new byte[4096]; int readLen; while ((readLen = fis.read(buffer)) != -1) { fos.write(buffer, 0, readLen); } fos.flush(); } catch (IOException | Resources.NotFoundException e) { e.printStackTrace(); // 可在此添加文件准备失败的Toast提示 return; } // 文件生成失败直接终止流程 if (!gifFile.exists()) return; Uri gifUri = FileProvider.getUriForFile( this, BuildConfig.APPLICATION_ID + ".provider", gifFile ); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("image/gif"); shareIntent.putExtra(Intent.EXTRA_STREAM, gifUri); // 给接收分享的应用授予文件读权限 shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(shareIntent, "分享到")); }
额外说明
如果GIF是从Firebase加载的,现有读取本地raw资源的逻辑和需求不符,不需要额外读取raw文件,直接在Firebase的下载回调中拿到输入流,写入缓存后再走上述分享逻辑即可。
内容的提问来源于stack exchange,提问作者anand agarwal
相关产品推荐
相关产品推荐

