Search code examples
androidimagefilescreenshotsharing

Sharing Screenshot on Android. Shares the same image every time


I have created a function that takes a screenshot, saves it in a temporary file of the type .jpeg, and then allows users to share it on facebook or bluetooth. Here is my share function:

public Bitmap Share(View v) {
    // Sound
    soundPool.play(button_sound, 1.0f, 1.0f, 0, 0, 1.0f);

    // Image
    v.setDrawingCacheEnabled(true);
    v.setLayerType(View.LAYER_TYPE_NONE, null);
    Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
    File file = new File(Environment.getExternalStorageDirectory()
            + File.separator + "temporary_file.jpg");
    try {
        file.createNewFile();
        FileOutputStream ostream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, ostream);
        ostream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Share
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");
    String filel = "file://" + Environment.getExternalStorageDirectory()
            + File.separator + "temporary_file.jpg";
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(filel));

    startActivity(Intent.createChooser(share, "Share Image"));
    return bitmap;
}

My problem is that it takes the screenshot, but then always shares the same screenshot over and over when I try to share a new one. When i check using the file manager, the image is different. SO I don't know what's causing that.

Thank you very much for you time.


Solution

  • First, file.createNewFile() only works when the file does not exist. It doesn't throw any exceptions when failed, it only returns true for success and false for fails,

    Same is true for bitmap.compress(Bitmap.CompressFormat.JPEG, 90, ostream); . This methods also doesn't throw any exceptions when failed, and only returns true for success and false for fails,

    I don't know if it it causing the error but you might want to look into that. You might try for example to delete the file first when it already exists.