I’ve created a Xamarin Forms (PCL) solution, and I’m focusing on the Android project at the moment. I’m trying to implement image sharing using a dependency service. The images are located in the drawable folder of the Android project. However, every time I run the code below, the app crashes with: an unhandled exception occurred. I've checked the output log but nothing stands out. Would anyone be able to run an eye over my code and tell me if there is an error in it?
Many thanks
Interface:
public interface IShare
{
void Share(ImageSource imageSource);
}
Xaml:
<ContentPage.Content>
<Image x:Name="LogoImage" Source="icon.png"/>
</ContentPage.Content>
Code-Behind:
private void Action_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IShare>().Share(LogoImage.Source);
}
ShareClass (in Android project):
[assembly: Dependency(typeof(ShareClass))]
namespace MyProject.Droid
{
public class ShareClass : Activity, IShare
{
public async void Share(ImageSource imageSource)
{
var intent = new Intent(Intent.ActionSend);
intent.SetType("image/png");
var handler = new ImageLoaderSourceHandler();
var bitmap = await handler.LoadImageAsync(imageSource, this);
var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads
+ Java.IO.File.Separator + "logo.png");
using (var os = new System.IO.FileStream(path.AbsolutePath, FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Png, 100, os);
}
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path));
Forms.Context.StartActivity(Intent.CreateChooser(intent, "Share Image"));
}
}
}