Share Image File from cache directory Via Intent~android

后端 未结 3 785
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 01:27

I am trying to share image file in cache directory, i have the complete path, but not able to send the file in attachments, the code is

File shareImage=Utils         


        
3条回答
  •  心在旅途
    2020-12-03 02:30

    I followed @CommonsWare's advice and used a FileProvider. Assuming your image is already in the internal cache directory as cache/images/image.png, then you can use the following steps. These are mostly a consolidation of the documentation.

    Set up the FileProvider in the Manifest

    
        ...
        
            ...
            
                
            
            ...
        
    
    

    Replace com.example.myapp with your app package name.

    Create res/xml/filepaths.xml

    
    
        
    
    

    This tells the FileProvider where to get the files to share (using the cache directory in this case).

    Share the image

    File imagePath = new File(context.getCacheDir(), "images");
    File newFile = new File(imagePath, "image.png");
    Uri contentUri = FileProvider.getUriForFile(context, "com.example.app.fileprovider", newFile);
    
    if (contentUri != null) {
    
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
        shareIntent.setDataAndType(contentUri, getContentResolver().getType(contentUri));
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        startActivity(Intent.createChooser(shareIntent, "Choose an app"));
    
    }
    

    Documentation

    • FileProvider
    • Storage Options - Internal Storage
    • Sharing Files
    • Saving Files

提交回复
热议问题