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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With