Share image in android from drawable

Here we again back with the new simple code snippet for android development.


Commonly developers don't want to prompt 'grant permissions' from users for basic things, Sharing your single image is also one of them. You can share the image from your application to another from drawable direct, don't need to access Storage permission.
Here is an example of How it is possible. Simply put your image in drawable folder of the android project. 


Configurations:-

Create xml directory in your project resource directory named 'provider_paths.xml' Create and put below code in that file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

After that put below code in your project manifest.xml file

1
2
3
4
5
6
7
8
9
<provider
      android:name="androidx.core.content.FileProvider"
      android:authorities="${applicationId}.provider"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/provider_paths" />
   </provider>

Finally Put the below code to your activity.java file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
sharebtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    File file = new File(getCacheDir()+"/shre.png");

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimagename);
    bitmap = createCertificate(bitmap);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));

    Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
    intent.putExtra(Intent.EXTRA_STREAM, uri);

    intent.putExtra(Intent.EXTRA_TEXT, "My image shared from AndroidApp...");
    intent.setType("image/*");
    startActivity(Intent.createChooser(intent, "send"));
    }
});

That enough of more task will make you skip the Grant Access permission from the user.

Happy Coding!
Thanks.

Comments