如何通过Intent Android从外部存储共享gif图像?

时间:2018-07-15 08:04:52

标签: android android-intent share gif animated-gif

我正在开发Animated Gif App,图像是从Web下载并存储在手机内存中的。然后,所有图像都完美地以动画形式显示在我的应用程序中,但是问题是当我通过已安装的手机应用程序共享它时。它不共享。图像的路径还可以,但仍然无法共享。我使用以下代码进行共享。请帮忙。

public static boolean shareImage(Context context, String imagePath) {
    File file = new File(imagePath);

    try {
        byte[] readData = new byte[1024 * 500];
        FileInputStream fis = new FileInputStream(file);

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

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

        fos.close();
    } catch (IOException io) {
        showToast(context, io.getLocalizedMessage());
    }      

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    String dataString = "MY_DATA_STRING";

    Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
    intent.setDataAndType(uri, dataString);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    intent.setType("image/gif");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    context.startActivity(Intent.createChooser(intent, context.getString(R.string.shareStickerTitle)));
    return true;
}

imagePath获得正确的路径,即如下所示

  

/sdcard/emulated/0/Android/data/PackageName/files/FolderName/xyz.gif

当“文件”转换为字节时,图像的bytes []变为(0),并且图像甚至在App中也被破坏并且不共享。

2 个答案:

答案 0 :(得分:1)

//Share Gif
public void shareGif(Context context, String fileName) {

    String baseDir = Environment.getExternalStorageDirectory().toString() + "/YourFolderName/";

    File file = new File(baseDir + "/" + fileName + ".gif");

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    String dataString = "MY_DATA_STRING";

    Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
    intent.setDataAndType(uri, dataString);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    intent.setType("image/gif");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    context.startActivity(Intent.createChooser(intent, "Share Emoji"));
}

答案 1 :(得分:0)

问题出在输入和输出流上。您在同一文件中读写。 希望您能从this link获得帮助。 这是使用Intent共享gif文件的正确方法。

您的try-catch块应如下所示。

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

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

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

    fos.close();
} catch (IOException io) {
}