Delete file after sharing via intent

前端 未结 4 785
轮回少年
轮回少年 2021-01-17 12:13

I\'m trying to delete a temporary file after sharing it via android\'s Intent.ACTION_SEND feature. Right now I am starting the activity for a result and in OnActivityResult,

4条回答
  •  太阳男子
    2021-01-17 12:28

    What I did is the following.

    I used the:

    myfile.deleteOnExit();
    

    However, as D.R. mentioned in the comment below correct answer, this does not guarantee the file deletion. This is why I am also deleting the file after the Shared Activity returns. I delete the file if file exists. Because the app crashed sometimes, I put it inside try{} and it works.

    I do not know why it does not work for you, but for me it works at least for Gmail attachement, TextSecure, Hangouts.

    In class delcaration:

    static File file;
    

    In method that calles 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 extra 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?");
            }
    
        }
    

提交回复
热议问题