java - "Cannot attach empty file"- 将内存中的图像共享到 Gmail 时

标签 java android

我正在尝试使用 Intent 共享存储在内部存储器中的图像。流程如下

  • 生成布局的位图
  • 将此位图保存到内部文件中
  • 内存使用 Intent 共享此文件(至 Gmail)

执行时似乎只生成空文件(因此无法附加到 Gmail)。我不确定代码从哪里开始变得困惑。所以,这是代码

生成和保存位图的方法

    public void generateAndSaveBitmap(View layout) {
//Generate bitmap
        layout.setDrawingCacheEnabled(true);
        layout.buildDrawingCache();
        Bitmap imageToSave = layout.getDrawingCache();
        layout.destroyDrawingCache();

//Create a file and path
        File directory = layout.getContext().getDir("images", Context.MODE_PRIVATE);
        File fileName = new File(directory, "sharableImage.jpg");
        if (fileName.exists())
            fileName.delete();

//Compress and save bitmap under the mentioned fileName
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//    return directory.getAbsolutePath();
    }

分享图像的方法

public void moreShareOptions(Context context) {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/jpg");
    File photoFile = new File("sharableImage.jpg");
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
    context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.opsh_share_this)));
}

这两个方法放在onClickListener内部如下

    case R.id.more_share_options:
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                optionsShareThis.generateAndSaveBitmap(toolbarWebView);
            }
        });

        t.start();
        optionsShareThis.moreShareOptions(this);
        break;

尝试找出问题所在。我错过了什么吗? 另外,我很想听到改进代码的建议(如果有的话)。

问候

编辑:

感谢您提及FileProvider。很高兴了解 getCacheDir。但是,即使使用 FileProvider 之后,我的代码仍继续返回空文件。我一直在探索多种资源,但无法生成具有上述布局的实际图像的文件。

generateAndSaveBitmap(View layout) - 未对此方法进行任何更改(上面提到的代码)。

下面是FileProvider相关的代码

AndroidManifest.xml - 没什么可讨论的新内容

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.android"
    android:exported="false"
    android:grantUriPermissions="true">

    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_path" />

</provider>

file_path.xml - 用于提及文件名及其路径

<?xml version="1.0" encoding="utf-8"?>

<paths>
    <files-path name="sharableImage" path="images/"/>
</paths>

moreShareOptions() -

    public void moreShareOptions(Context context) {

// concatenate the internal cache folder with the document its path and filename
        final File file = new File(context.getFilesDir(), "images/sharableImage.jpg");
// let the FileProvider generate an URI for this private file
        final Uri uri = FileProvider.getUriForFile(context, "com.example.android", file);
// create an intent, so the user can choose which application he/she wants to use to share this file

        final Intent intent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            intent = ShareCompat.IntentBuilder.from((Activity) context)
                    .setType("image/jpg")
                    .setStream(uri)
                    .createChooserIntent()
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            context.startActivity(intent);
        }else {
        intent = ShareCompat.IntentBuilder.from((Activity) context)
                .setType("image/jpg")
                .setStream(uri)
                .createChooserIntent()
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            context.startActivity(intent);
        }
    }

我错过了什么?我花了几个小时寻找获得必要结果的方法。没什么成果。因此,我发布这段代码,希望其他人能够指出我哪里出错了。

最佳答案

第三方应用无权访问您的内部存储空间。并且,特别是从 Android N 开始,sharing files is strongly discouraged in general .

相反,use FileProvider to share the contentthe documentation 中也对此进行了介绍。 .

关于java - "Cannot attach empty file"- 将内存中的图像共享到 Gmail 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36802977/

相关文章:

java - flutter 说它 'Could not resolve project'

android - 我可以让 webview 只占据屏幕的一部分吗?

java - -> 运算符在 grails 中的含义和用法是什么?

java - 防止应用程序在两个实例上运行

java - Android 中无损图像保存的其他选项?

android - WebView 在 Android 9.0 中没有加载页面?

java - Java 中的可排序 HTML 表格

java - 如何从数据库传递两个变量以显示到android中的数组中

android - 索引 2 处不透明部分的非法字符 flutter

android - 从 android 的 Intent 中获取值