如何使用意图共享将gif图片分享给可用的应用程序?

8

我希望能够通过可用的应用程序(如WhatsApp)共享.gif文件,但无法获取我的可绘制资源中gif的有效Uri。

 Uri path = Uri.parse("android.resource://my_package_name/" + R.drawable.gif_1);
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("image/gif");
    shareIntent.putExtra(Intent.EXTRA_STREAM, path);

在分享图片方面有很多解决方案,但是在GIF分享方面却没有解决方案,请帮忙。

2个回答

15
我找到了答案,我只是创建了一个扩展名为.gif的文件,这对我有用。请参见下面的代码:

我找到了答案,我只需要创建一个带有 .gif 扩展名的文件,它就能正常工作。请看下面的代码:

private void shareGif(String resourceName){

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    String fileName = "sharingGif.gif";

    File sharingGifFile = new File(baseDir, fileName);

    try {
        byte[] readData = new byte[1024*500];
        InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));

        FileOutputStream fos = new FileOutputStream(sharingGifFile);
        int i = fis.read(readData);

        while (i != -1) {
            fos.write(readData, 0, i);
            i = fis.read(readData);
        }

        fos.close();
    } catch (IOException io) {
    }
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("image/gif");
    Uri uri = Uri.fromFile(sharingGifFile);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}

如果gif在服务器上怎么办? - Butani Vijay
@ButaniVijay:本地下载gif,然后使用相同的代码进行分享 :) - Anand Savjani
1
如果我的 GIF 文件位于 drawable 文件夹中,那么在 resourcename 中应该传递什么? - jigar savaliya
@ButaniVijay:我使用了你的代码,但是失败了。我的图片在服务器上,我将其下载到存储中,然后获取确切的路径,但是我的应用程序仍然崩溃,并且日志中没有错误消息来消除错误。 - Zia Ur Rahman
这段代码不起作用。只分享了静态图像,没有动画gif。 - erKaranjeet

0
if you want to take image from internal storage.

//this is method having internal storage path.
 private String getFilePath2() {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/Gifs temp/");
    if (!myDir.exists())
        myDir.mkdirs();
    String fname = "temp_gif";
    SimpleDateFormat timeStampFormat = new SimpleDateFormat(
            "yyyyMMdd_HHmmss");
    Date myDate = new Date();
    String filename = timeStampFormat.format(myDate);
    File file = new File(myDir, fname + "_" + filename + ".gif");
    if (file.exists()) {
        file.delete();
    }
    String str = file.getAbsolutePath();
    return str;
}




 //   Then take image from internal storage into the string.
  String st = getFilePath2();




 //And share this by this intent
 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
                            shareIntent.setType("image/gif");
                            Uri uri = Uri.fromFile(sharingGifFile);
                            shareIntent.putExtra(Intent.EXTRA_STREAM,        
  uri);

  startActivity(Intent.createChooser(shareIntent, "Share Emoji"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接