Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Android: Share image via standard api (email, facebook etc.)

I need to implement standard sharing in Xamarin Android. I found and changed code for Xamarin. It looks like this

    public void Share (string title, string content)
    {
        if (string.IsNullOrEmpty (title) || string.IsNullOrEmpty (content))
            return;

        var name = Application.Context.Resources.GetResourceName (Resource.Drawable.icon_120).Replace (':', '/');
        var imageUri = Uri.Parse ("android.resource://" + name);
        var sharingIntent = new Intent ();
        sharingIntent.SetAction (Intent.ActionSend);
        sharingIntent.SetType ("image/*");
        sharingIntent.PutExtra (Intent.ExtraText, content);
        sharingIntent.PutExtra (Intent.ExtraStream, imageUri);
        sharingIntent.AddFlags (ActivityFlags.GrantReadUriPermission);
        ActivityContext.Current.StartActivity (Intent.CreateChooser (sharingIntent, title));
    }

This code call standard share function, but when i choose Facebook or email, i am getting "Cant load image". File is located in "/Resources/drawable-xhdpi/icon_120.png".

Can you point me what i am doing wrong?

like image 564
F0rc0sigan Avatar asked Jul 27 '15 20:07

F0rc0sigan


1 Answers

I think the app icon is created in a directory that is private to your app, so other apps wont be able to get at it.

You will need to save it out somewhere where the other apps can access it then share it from that location some thing like this:

public void Share (string title, string content)
{
    if (string.IsNullOrEmpty (title) || string.IsNullOrEmpty (content))
                return;

    Bitmap b = BitmapFactory.DecodeResource(Resources,Resource.Drawable.icon_120);

    var tempFilename = "test.png";
    var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
    var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
    using (var os = new FileStream(filePath, FileMode.Create))
    {
        b.Compress(Bitmap.CompressFormat.Png, 100, os);
    }
    b.Dispose ();

    var imageUri = Android.Net.Uri.Parse ($"file://{sdCardPath}/{tempFilename}");
    var sharingIntent = new Intent ();
    sharingIntent.SetAction (Intent.ActionSend);
    sharingIntent.SetType ("image/*");
    sharingIntent.PutExtra (Intent.ExtraText, content);
    sharingIntent.PutExtra (Intent.ExtraStream, imageUri);
    sharingIntent.AddFlags (ActivityFlags.GrantReadUriPermission);
    StartActivity (Intent.CreateChooser (sharingIntent, title));
}

Also add ReadExternalStorage and WriteExternalStorage permissions to your app.

Let me know if that works.

like image 150
Iain Smith Avatar answered Oct 16 '22 02:10

Iain Smith