How to use "Share image using" sharing Intent to share images in android?
Asked Answered
S

17

95

I have an image galley app; in that app I placed all the images into the drawable-hdpi folder. I call images in my activity like this:

private Integer[] imageIDs = {
        R.drawable.wall1, R.drawable.wall2,
        R.drawable.wall3, R.drawable.wall4,
        R.drawable.wall5, R.drawable.wall6,
        R.drawable.wall7, R.drawable.wall8,
        R.drawable.wall9, R.drawable.wall10
};

How do I share these images using sharing Intent? I put sharing code like this:

     Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
       
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  
    
         }
    });

And I have a sharing button also; when I click on the share button, the Sharing box is opening, but when I click any service, mostly it's crashing or some services say: "unable to open image". How can I fix this or is there any other format code to share images?

I tried using the code below, but it's not working.

Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
        try {
            InputStream stream = getContentResolver().openInputStream(screenshotUri);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  

         }
    });

How do I share my images from the drawable-hdpi folder?

Sycamine answered 5/10, 2011 at 13:17 Comment(4)
you are passing whole array into URI parse methodEntomb
You are setting up wrong URI. That's why this problem arises. Again you are trying to share multiple images so you must use #2265122.. And for setting up correct URI you should try #6602917Ankeny
help me here #31826994Martyry
check this tutorial share image from drawable folderAligarh
G
123
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {                       
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Geneviegenevieve answered 5/10, 2011 at 13:38 Comment(15)
Is there a reason against using File f = File.createTempFile("sharedImage", suffix, getExternalCacheDir());, and the use share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); ?Locution
And a minor: According to IANA the correct MIME for JPEGs is image/jpeg (note the "e").Locution
Yes, if you use createTempFile, then the file is created in a directory that is private to your app. Thus, other apps (i.e., the ones you are sharing with) will be unable to retrieve the image.Eliga
Also you should close the output stream.Tirzah
@Geneviegenevieve Hello Can we share picture and text at same share Intents?Newberry
@Maid786, It's been ages since I worked with Android, but I believe we can share any file by setting the corresponding type and location.Geneviegenevieve
For me this approach does not work for most Apps on Android 4.4.2, the image can't be read by most apps. GMail for example crashes with a NP-Exception, maybe because the MediaStore is not used (see answer below)?Slake
@Geneviegenevieve can u help me how can i share from drawable folderRusell
1.) Don't forget to close your FileOutputStream. 2.) Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() insteadSelfrenunciation
If you get EACCES (Permission denied) error, add the following to your AndroidManifest.xml: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></code>Icbm
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object referenceMartyry
i am getting this error near this line icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);Martyry
The above solution works ok, but as is mentioned in a comment and lint inspection, you shouldn't hardcode the file directory when parsing. However if you just change it to Environment.getExternalStorageDirectory, this will evaluate to the path without the protocol (ie "/storage/emulated/0/...") In order for the Uri to resolve in the next activity it will need "file:///" + path in front of it. Or you could use Uri.fromFile(f) instead of Uri.parse()Yardage
Wont this create a temporary file in users gallary? Which he should not see.Taction
can we pass request code with this intent, so that we can do some specific task when it comes back?Placer
B
52

The solution proposed from superM worked for me for a long time, but lately I tested it on 4.2 (HTC One) and it stopped working there. I am aware that this is a workaround, but it was the only one which worked for me with all devices and versions.

According to the documentation, developers are asked to "use the system MediaStore" to send binary content. This, however, has the (dis-)advantage, that the media content will be saved permanently on the device.

If this is an option for you, you might want to grant permission WRITE_EXTERNAL_STORAGE and use the system-wide MediaStore.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
Briant answered 27/10, 2013 at 13:13 Comment(4)
This is the only solution that worked for me to share in Facebook! Thanks.Magallanes
This creates a new image. How do I delete the new image?Slusher
@BlueMango did you find a solution?Taction
Perfect answer! Works in every app!Jidda
B
31

First add permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

using Bitmap from resources

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri =  Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));

Tested via bluetooth and other messengers

Brierroot answered 7/5, 2015 at 9:20 Comment(9)
how to send image from url like whats app and allRathe
if you want to Share image from url to Another App .You need to download the image to Bitmap #18211200 and then use share intent .Brierroot
and then after attached image and shared how to close that app and go to our app androidRathe
@Rathe lol. FYI , u can not handle that if someone leave ur app some how . he/she have to go to recent and resume ur app .no other way . how can u take control on someone else's app?.Brierroot
#31826994Martyry
There's no need to create BufferedOutputStream and compress the bitmap because compressed result is not used anywhere.Nadeen
@Nadeen this function returns True False (developer.android.com/reference/android/graphics/…)Brierroot
MediaStore.Images.Media.insertImage is deprecated since API 29.Lurlinelusa
Tested on Android real device - 10,11,12 and working very fine. Thank you so much for your helpful code.Kendrakendrah
H
30

I found the easiest way to do this is by using the MediaStore to temporarily store the image that you want to share:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From: Sharing Content With Intents

Hillegass answered 18/9, 2015 at 13:3 Comment(3)
There's no need for the canvas variable, it is not used anywhere.Balenciaga
do not forget to add ermission to manifest.xml: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Roughhouse
MediaStore.Images.Media.insertImage is depricatedTreacle
N
15

Simple and Easiest code you can use it to share image from gallery.

String image_path = "path/to/your/image";
File file = new File(image_path);
Uri uri = Uri.fromFile(file);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);

context.startActivity(intent);
Nagging answered 7/3, 2016 at 10:45 Comment(1)
Simple and powerful, no need to save image or what so ever, all above answers did not worked for me but this simple solution does the trick...Thank yo very much....By the way I have tested this code on my phone with oreo version of androidDelorenzo
P
14

Thanks all, I tried the few of the options given, but those seems not to work for the latest android releases, so adding the modified steps which work for the latest android releases. these are based on few of the answers above but with modifications & the solution is based on the use of File Provider :

Step:1

Add Following code in Manifest File:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_provider_paths" />
</provider>

step:2 Create an XML File in res > xml

Create file_provider_paths file inside xml.

Note that this is the file which we include in the android:resource in the previous step.

Write following codes inside the file_provider_paths:

<?xml version="1.0" encoding="utf-8"?>
<paths>
        <cache-path name="cache" path="/" />
        <files-path name="files" path="/" />
</paths>

Step:3

After that go to your button Click:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

       Bitmap bit = BitmapFactory.decodeResource(context.getResources(),  R.drawable.filename);
        File filesDir = context.getApplicationContext().getFilesDir();
        File imageFile = new File(filesDir, "birds.png");
        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bit.compress(Bitmap.CompressFormat.PNG, 100, os); 
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);

        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        intent.setType("image/*");
        context.startActivity(intent);
    }
});

For More detailed explanation Visit https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/

Perrotta answered 6/8, 2020 at 21:26 Comment(2)
This is the right answerKnecht
Thanks! This worked great! 2 suggestions for anyone having trouble: --- BuildConfig was not a recognized class, but I found you can use getPackageName() instead of BuildConfig.APPLICATION_ID --- The share type didn't seem like the type normally used; What worked better for me was to use startActivity(Intent.createChooser(intent, "Share Via")); instead of context.startActivity(intent);Dario
J
13

How to share image in android progamatically , Sometimes you wants to take a snapshot of your view and then like to share it so follow these steps: 1.Add permission to mainfest file

<uses-permission    
   android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2.Very First take a screenshot of your view , for example it is Imageview, Textview, Framelayout,LinearLayout etc

For example you have an image view to take screenshot call this method in oncreate()

 ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
     ///take a creenshot
    screenShot(image);

after taking screenshot call share image method either on button
click or where you wants

shareBitmap(screenShot(image),"myimage");

After on create method define these two method ##

    public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
    try {
        File file = new File(getContext().getCacheDir(), fileName + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(     android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
Juniejunieta answered 15/3, 2017 at 11:0 Comment(1)
What is the ".setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);" used for in the intent you set up above?Kymry
M
11

Here is a solution that worked for me. One gotcha is you need to store the images in a shared or non app private location (http://developer.android.com/guide/topics/data/data-storage.html#InternalCache)

Many suggestions say to store in the Apps "private" cache location but this of course is not accessable via other external applications, including the generic Share File intent which is being utilised. When you try this, it will run but for example dropbox will tell you the file is no longer available.

/* STEP 1 - Save bitmap file locally using file save function below. */

localAbsoluteFilePath = saveImageLocally(bitmapImage);

/* STEP 2 - Share the non private Absolute file path to the share file intent */

if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(localAbsoluteFilePath);

    File file = new File(phototUri.getPath());

    Log.d(TAG, "file path: " +file.getPath());

    if(file.exists()) {
        // file create success

    } else {
        // file create fail
    }
    shareIntent.setData(phototUri);
    shareIntent.setType("image/png");
    shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
    activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}   

/* SAVE IMAGE FUNCTION */

    private String saveImageLocally(Bitmap _bitmap) {

        File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
        File outputFile = null;
        try {
            outputFile = File.createTempFile("tmp", ".png", outputDir);
        } catch (IOException e1) {
            // handle exception
        }

        try {
            FileOutputStream out = new FileOutputStream(outputFile);
            _bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

        } catch (Exception e) {
            // handle exception
        }

        return outputFile.getAbsolutePath();
    }

/* STEP 3 - Handle Share File Intent result. Need to remote temporary file etc. */

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            // deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
        if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
            // delete temp file
            File file = new File (localAbsoluteFilePath);
            file.delete();

            Toaster toast = new Toaster(activity);
            toast.popBurntToast("Successfully shared");
        }


    }   

I hope that helps someone.

Mccully answered 5/2, 2014 at 22:52 Comment(3)
your use of Log.d is backward. It's tag first then message.Feat
fixed, I don't actually use log.d, I have a wrapper function. I must made a typo when i changed the example to make appropriate for SO. CheersMccully
#31826994Martyry
O
8

I was tired in Searching different options for sharing view or image from my application to other application . And finally i got the solution.

Step 1 : Share Intent handling Block. This will Pop Up your window with list of Applications in you phone

public void share_bitMap_to_Apps() {

    Intent i = new Intent(Intent.ACTION_SEND);

    i.setType("image/*");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    /*compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();*/


    i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
    try {
        startActivity(Intent.createChooser(i, "My Profile ..."));
    } catch (android.content.ActivityNotFoundException ex) {

        ex.printStackTrace();
    }


}

Step 2 : Converting your view to BItmap

public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),      view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}

Step 3 :

To get The URI from Bitmap Image

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}
Outstay answered 16/8, 2016 at 4:10 Comment(0)
A
4

I just had the same problem.
Here is an answer that doesn't use any explicit file writing in your main code (letting the api taking care of it for you).

Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));

This is the path... you just need to add your image IDs in a Drawable object. In my case (code above), the drawable was extracted from an ImageView.

Adoration answered 6/9, 2015 at 6:18 Comment(0)
V
3

SuperM answer worked for me but with Uri.fromFile() instead of Uri.parse().

With Uri.parse(), it worked only with Whatsapp.

This is my code:

sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));

Output of Uri.parse():
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Output of Uri.fromFile:
file:///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Violante answered 17/7, 2015 at 7:38 Comment(0)
C
3

ref :- http://developer.android.com/training/sharing/send.html#send-multiple-content

ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
Changeling answered 2/12, 2015 at 11:7 Comment(0)
W
3

All the Above solution doesnot work for me in Android Api 26 & 27 (Oreo), was gettting Error: exposed beyond app through ClipData.Item.getUri. The solution that fits in my situation was

  1. get path uri using FileProvider.getUriForFile(Context,packagename,File) as
void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
        startActivity(Intent.createChooser(intent,"Share with..."));
    }
  1. Define a <provider> in your Manifest.xml as
<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.example.stickerapplication"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths">
       </meta-data>
</provider>
  1. And the last step is to define resource file for your directorys
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`
Wordage answered 28/1, 2019 at 6:54 Comment(0)
N
2

A perfect solution for share text and Image via Intent is :

On your share button click :

Bitmap image;
shareimagebutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            URL url = null;
            try {
                url = new URL("https://firebasestorage.googleapis.com/v0/b/fir-notificationdemo-dbefb.appspot.com/o/abc_text_select_handle_middle_mtrl_light.png?alt=media&token=c624ab1b-f840-479e-9e0d-6fe8142478e8");
                image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            shareBitmap(image);
        }
    });

Then Create shareBitmap(image) method.

private void shareBitmap(Bitmap bitmap) {

    final String shareText = getString(R.string.share_text) + " "
            + getString(R.string.app_name) + " developed by "
            + "https://play.google.com/store/apps/details?id=" + getPackageName() + ": \n\n";

    try {
        File file = new File(this.getExternalCacheDir(), "share.png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(Intent.createChooser(intent, "Share image via"));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

And then just test It..!!

Narvaez answered 9/9, 2018 at 7:13 Comment(0)
T
1

With implementation of stricter security policies, exposing uri outside of app throws an error and application crashes.

@Ali Tamoor's answer explains using File Providers, this is the recommended way.

For more details see - https://developer.android.com/training/secure-file-sharing/setup-sharing

Also you need to include androidx core library to your project.

implementation "androidx.core:core:1.2.0"

Of course this is bit bulky library and need it just for sharing files -- if there is a better way please let me know.

Telfore answered 27/3, 2020 at 20:9 Comment(0)
P
1
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        Log.d(TAG, "Permission granted");
    } else {
        ActivityCompat.requestPermissions(getActivity(),
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                100);
    }

    fab.setOnClickListener(v -> {
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/*");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
                b, "Title", null);
        Uri imageUri = Uri.parse(path);
        share.putExtra(Intent.EXTRA_STREAM, imageUri);
        share.putExtra(Intent.EXTRA_TEXT, "Here is text");
        startActivity(Intent.createChooser(share, "Share via"));
    });
Prunella answered 23/12, 2020 at 8:42 Comment(1)
Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the tour, and How do I write a good answer? You can add information why is that answer better than other answers to this question.Cully
H
0
Strring temp="facebook",temp="whatsapp",temp="instagram",temp="googleplus",temp="share";

    if(temp.equals("facebook"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
        if (intent != null) {

            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image/png");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setPackage("com.facebook.katana");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Facebook require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("whatsapp"))
    {

        try {
            File filePath = new File("/sdcard/folder name/abc.png");
            final ComponentName name = new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker");
            Intent oShareIntent = new Intent();
            oShareIntent.setComponent(name);
            oShareIntent.setType("text/plain");
            oShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Website : www.google.com");
            oShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));
            oShareIntent.setType("image/jpeg");
            oShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            MainActivity.this.startActivity(oShareIntent);


        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "WhatsApp require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("instagram"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
        if (intent != null)
        {
            File filePath =new File("/sdcard/folder name/"abc.png");
            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/Chitranagari/abc.png"));
            shareIntent.setPackage("com.instagram.android");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Instagram require..!!", Toast.LENGTH_SHORT).show();

        }
    }
    if(temp.equals("googleplus"))
    {

        try
        {

            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
            String strDate = sdf.format(c.getTime());
            Intent shareIntent = ShareCompat.IntentBuilder.from(MainActivity.this).getIntent();
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setPackage("com.google.android.apps.plus");
            shareIntent.setAction(Intent.ACTION_SEND);
            startActivity(shareIntent);
        }catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Googleplus require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("share")) {

        File filePath =new File("/sdcard/folder name/abc.png");  //optional //internal storage
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));  //optional//use this when you want to send an image
        shareIntent.setType("image/jpeg");
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "send"));

    }
Hun answered 16/4, 2016 at 5:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.