I did the following.
I used:
myfile.deleteOnExit();
However, as DR the correct answer mentioned in the comment below does not guarantee file deletion. That is why I also delete the file after the Shared Activity returns. I delete the file if the file exists. Since the application sometimes crashes, I put it inside try{} and it works.
I donβt know why this does not work for you, but for me it works, at least for attaching Gmail, TextSecure, Hangouts.
In the delcaration class:
static File file;
In the method that causes the intent:
Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/png"); // Compress the bitmap to PNG ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes); // Temporarily store the image to Flash File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdCard.getAbsolutePath() + "/FolderName"); dir.mkdirs(); // This file is static. file = new File(dir, "FileName.png"); try { file.createNewFile(); FileOutputStream fo = new FileOutputStream(file); fo.write(bytes.toByteArray()); fo.flush(); fo.close(); } catch (IOException e) { e.printStackTrace(); } // Share compressed image share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///"+file.getPath())); /** START ACTIVITY **/ startActivityForResult(Intent.createChooser(share,"Share Image"),1); // Delete Temporary file file.deleteOnExit(); // sometimes works
In an additional method
protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Because app crashes sometimes without the try->catch try { // if file exists in memory if (file.exists()) { file.delete(); } } catch (Exception e) { Log.d(LOG,"Some error happened?"); } }
source share