尝试共享图片时出错

时间:2015-05-12 19:54:46

标签: java android image android-studio share

所以我拍摄了我的活动截图,然后将其保存到“screenshot.png”。当试图分享它,让我们说,Whatsapp,我得到一个错误:“无法发送图像”。与gmail,pushbullet和基本上所有其他应用程序相同。因此,我得出结论,文件以某种方式存在,但它要么是空的,要么搞砸了......我真的不知道。

以下是代码:

参加活动截图:

public Bitmap takeScreenshot() {
        View rootView = findViewById(android.R.id.content).getRootView();
        rootView.setDrawingCacheEnabled(true);
        return rootView.getDrawingCache();
    }

保存屏幕截图:

public void saveBitmap(Bitmap bitmap) {
        FileOutputStream fos;
        String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
        File f = new File(filePath);
        try {
            fos = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("GREC", e.getMessage(), e);
        } catch (IOException e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }

最后,共享本身:

if (id == R.id.action_share){
            Bitmap bitmap = takeScreenshot();
            saveBitmap(bitmap);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/png");
            share.putExtra(Intent.EXTRA_STREAM, Uri.parse("screenshot.png"));
            startActivity(Intent.createChooser(share, "Teilen via"));
        }

我的错误在哪里?我没有在logcat中收到任何错误,但我无法分享“截图”。

1 个答案:

答案 0 :(得分:1)

首先,你应该使用:

share.putExtra(Intent.EXTRA_STREAM. Uri.fromFile(new File(getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png"));

但是你会得到“附件的权限被拒绝”你可能会尝试但没有运气:(

share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

处理此问题的最佳方法可能是将捕获的屏幕截图存储在媒体库中并从那里发送文件。

public void share() {
    String filePath=getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
    String path;
    try {
        path = Images.Media.insertImage(getContentResolver(), filePath, "title", null);
        Uri screenshotUri = Uri.parse(path);

        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/png");
        share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(share, "Teilen via"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

希望它会有所帮助!

相关问题