android share image in ImageView without saving in sd card

前端 未结 3 1192
一生所求
一生所求 2021-02-05 15:55

I want to Share the image in image view.but i don\'t want save to SDcard. But when i use Intent to share i used code

Intent share = new Intent(Intent.ACTION_         


        
3条回答
  •  醉梦人生
    2021-02-05 16:47

    The recommended method for sharing files with other apps is with a ContentProvider called FileProvider. The documentation is pretty good, but some parts are a little tricky. Here is a summary.

    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).

    Save the image to internal storage

    // save bitmap to cache directory
    try {
    
        File cachePath = new File(context.getCacheDir(), "images");
        cachePath.mkdirs(); // don't forget to make the directory
        FileOutputStream stream = new FileOutputStream(new File(cachePath, "image.png")); // overwrites this image every time
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();
    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    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"));
    
    }
    

    Further reading

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

提交回复
热议问题