13

I am integrating share with the following code for the app.

private void socialShare()
    {
        Uri uri = Uri.parse("android.resource://com.example.myproject/drawable/appicon");
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "sharing myapp");
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, "Share from"));
    }

As in the above code, I am trying to put png image which is in drawable folder. But the image is unable to be sent. Is that because in setType, it's image/jpeg? I can't use jpeg, because it loses transparency. Can some one please suggest me how to share with image?

Here is the code that I use to copy the image from drawable to sdcard:

String commonPath = Environment.getExternalStorageDirectory().toString() + "/MyAppFolder"; 
        File direct = new File(commonPath);

        if(!direct.exists())
        {
            if(direct.mkdir()) 
              {
                Log.d("tag","directory created");
               //directory is created;
              }

        }

        Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.sharingimage);
        OutputStream outStream = null;
           File savingFile = new File(commonPath, "shareImage.png");
           if(!savingFile.exists())
           {
               Log.d("tag","file is created");

           try {
                savingFile.createNewFile();
                outStream = new FileOutputStream(savingFile);
                bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();

                Log.d("tag","Saved");

               } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

               } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

               }

            }
rick
  • 4,665
  • 10
  • 27
  • 44

6 Answers6

18

I found solution where I should not copy image on sd card. Here it is:

    try {
        Uri imageUri = null;
        try {
            imageUri = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.fragment_menu_logo), null, null));
        } catch (NullPointerException e) {
        }
        String text = getString(R.string.share_text);
        // Launch the Google+ share dialog with attribution to your app.
        Intent shareIntent = new PlusShare.Builder(mActivity)
                .setType("image/*")
                .setText(text)
                .addStream(imageUri)
                .getIntent();
        startActivity(shareIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(mActivity, mActivity.getString(R.string.share_google_plus_not_installed), Toast.LENGTH_LONG).show();
    }
Ruslan Mansurov
  • 1,281
  • 16
  • 23
11
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.xxxx);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/LatestShare.jpg";
OutputStream out = null;
File file=new File(path);
try {
    out = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}
path=file.getPath();
Uri bmpUri = Uri.parse("file://"+path);
Intent shareIntent = new Intent();
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/jpg");
startActivity(Intent.createChooser(shareIntent,"Share with"));

This works for me perfectly, and this will need write permission

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

Add this line to android manifest for the write permission.

Ashok Varma
  • 3,489
  • 3
  • 28
  • 43
10

You can share using the following method...

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/png");
Uri uri = Uri.parse("android.resource://your package name/"+R.drawable.ic_launcher);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, This is test Sharing");
startActivity(Intent.createChooser(shareIntent, "Send your image"));

Tried and tested...working for me

Mit
  • 318
  • 2
  • 10
6

First add permission

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

use Bitmap from res

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.

Works like a Charm.

Hemant Shori
  • 2,463
  • 1
  • 22
  • 20
  • 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 reference – Nouman Ch Sep 13 '18 at 12:13
  • //open the share sheet Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_14_cold_turkey); Intent share = new Intent(Intent.ACTION_SEND); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), b, "ColdTurkey", null); – Nouman Ch Sep 13 '18 at 12:14
  • 1
    Uri imageUri = Uri.parse(path); share.putExtra(Intent.EXTRA_STREAM, imageUri); share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); share.setType("image/png"); startActivity(share); – Nouman Ch Sep 13 '18 at 12:14
2

No need for a permission. No need to implement a content provider.

This is what you need:

Manifest:

        <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/provider_paths" />
        </provider>

res/xml/provider_paths.xml

<paths>
    <cache-path
        name="cache_root" path="." />
</paths>

And the code to use its Intent:

@WorkerThread
fun shareDrawable(context: Context, @DrawableRes resourceId: Int, fileName: String): Intent {
    val bitmap = ResourcesCompat.getDrawable(context.resources, resourceId, null)!!.toBitmap()
    val outputFile = File(context.cacheDir, "$fileName.png")
    val outPutStream = FileOutputStream(outputFile)
    bitmap.compress(CompressFormat.PNG, 100, outPutStream)
    outPutStream.flush()
    outPutStream.close()
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.putExtra(Intent.EXTRA_STREAM, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        androidx.core.content.FileProvider.getUriForFile(context, context.packageName, outputFile)
    else
        Uri.fromFile(outputFile))
    shareIntent.type = "image/png"
    return shareIntent
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
1

You can not directly share a uri from you apps internal storage (of course the resourses of your app will be always in the internal storage)

There are two ways of achieving this..

  1. Copy your image to external storage then share it from there. See this

  2. Write a Content Provider to share image. For that refer Create and Share a File from Internal Storage

Community
  • 1
  • 1
Arun C
  • 9,035
  • 2
  • 28
  • 42
  • Thanks for your answer. But I am unable to make it with the first way. – rick Aug 29 '13 at 06:06
  • did you copy the image into external storage – Arun C Aug 29 '13 at 06:29
  • No. I am unable to copy the image. It always throws file not found exception. Can you please show me code snippet if you already have it? – rick Aug 29 '13 at 06:58
  • Please follow this link http://stackoverflow.com/a/10561536/1051147 And dontforget to add permission to access SD CARD. – Arun C Aug 29 '13 at 07:00
  • Make sure that your file names are correct.. and post the code that you have done.. – Arun C Aug 29 '13 at 07:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36440/discussion-between-rick-and-tca) – rick Aug 29 '13 at 07:18
  • the image gets attached but it remains an unreadable file. why? –  Mar 11 '14 at 12:41