Android Share Intent for a Bitmap - is it possible not to save it prior sharing?

前端 未结 5 711
遇见更好的自我
遇见更好的自我 2020-11-27 10:12

I try to export a bitmap from my app using share intent without saving a file for a temporal location. All the examples I found are two-step 1) save to SD Card and create U

5条回答
  •  悲哀的现实
    2020-11-27 10:36

    If anyone still looking for easy and short solution without any storage permission (Supports nougat 7.0 as well). Here it is.

    Add this in Manifest

    
         
     
    

    Now create provider_paths.xml

    
        
    
    

    Finally Add this method to your activity/fragment (rootView is the view you want share)

     private void ShareIt(View rootView){
            if (rootView != null && context != null && !context.isFinishing()) {
                rootView.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
                if (bitmap != null ) {
                     //Save the image inside the APPLICTION folder
                    File mediaStorageDir = new File(AppContext.getInstance().getExternalCacheDir() + "Image.png");
    
                    try {
                        FileOutputStream outputStream = new FileOutputStream(String.valueOf(mediaStorageDir));
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                        outputStream.close();
    
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                    if (ObjectUtils.isNotNull(mediaStorageDir)) {
    
                        Uri imageUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", mediaStorageDir);
    
                        if (ObjectUtils.isNotNull(imageUri)) {
                            Intent waIntent = new Intent(Intent.ACTION_SEND);
                            waIntent.setType("image/*");
                            waIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                            startActivity(Intent.createChooser(waIntent, "Share with"));
                        }
                    }
                }
            }
        }
    

    Update:

    As @Kathir mentioned in comments,

    DrawingCache is deprecated from API 28+. Use below code to use Canvas instead.

     Bitmap bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), quality);
        Canvas canvas = new Canvas(bitmap);
    
        Drawable backgroundDrawable = view.getBackground();
        if (backgroundDrawable != null) {
            backgroundDrawable.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
    
        return bitmap;
    

提交回复
热议问题