Sharing current view via ACTION_SEND without storing the image in android

1.3k views Asked by At

I want to share the current view of the app using ACTION_SEND.

The method of converting the current view to bitmap and storing it in external storage for converting the bitmap to a parsable Uri needs permissions.

Snippet:

    public static Bitmap getScreenShot(View view) {
        View screenView = view.getRootView();
        screenView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
        screenView.setDrawingCacheEnabled(false);
        return bitmap;
    }

    // View to BitMap
    Bitmap b  = getScreenShot(getWindow().getDecorView().findViewById(android.R.id.content));

    //BitMap to Parsable Uri (needs write permissions)
    String pathofBmp = MediaStore.Images.Media.insertImage(getContentResolver(), b,"title", null);
    Uri bmpUri = Uri.parse(pathofBmp);

    //Share the image
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "send"));

This needs WRITE_EXTERNAL_STORAGE permission, Is there a way to perform the same without storing it in external storage (without permissions) on Android?

1

There are 1 answers

3
CommonsWare On BEST ANSWER

If your minSdkVersion is 19 or higher, you can use getExternalFilesDir() to write the image to external storage and avoid the permission issue.

You can write the file to internal storage (e.g., getCacheDir()), then share it using FileProvider. You need to use FileProvider or some ContentProvider going forward anyway, as Android 7.0+ does not like the file scheme.

If you want to avoid the disk I/O... you would have to compress the Bitmap to a ByteArrayOutputStream, then write your own ContentProvider to serve from that byte[]. This is somewhat risky, in that if your process is terminated before the other app winds up trying to use the Uri, you are out of luck, as your bitmap is gone.