I developed a dependency service for sending an email from xamarin.forms. This used to work just fine. But, after a few Xamarin.Forms updates and related Xamarin.Android... API updates, this stopped working. At one point, I had to change the way I get the context to call the StartActivity(email) method.
Now, the email activity starts and I am able to send the email, but the app that called it crashes. And, I cannot figure out why. Is there something that I am doing wrong?
Method in common project (NetStandard 1.6)
private async Task EmailFileAsync(EmailContent emailContent)
{
var emailer = DependencyService.Get();
Tuple<bool, string> response = new Tuple<bool, string>(false, "Unable to get an Email Manager from the device. ");
if (emailer != null)
{
response = await emailer.SendEmailAsync(emailContent);
}
if (!response.Item1)
{
await DisplayAlert("Send TRN Failure", response.Item2, "OK");
}
return response.Item1;
}
Dependency Service in Android project
using Android.App;
using Android.Content;
using System;
using System.IO;
using System.Threading.Tasks;
using TPS_Mobile_NS.Droid.InterfacesImplemented;
using TPS_Mobile_NS.Interfaces;
using TPS_Mobile_NS.Models;
using Xamarin.Forms;
[assembly: Dependency(typeof(EmailManager))]
namespace TPS_Mobile_NS.Droid.InterfacesImplemented
{
public class EmailManager : Activity, IEmailManager
{
public Task<Tuple<bool, string>> SendEmailAsync(EmailContent emailContent)
{
var sendWasSuccessful = false;
var errorMessage = string.Empty;
try
{
var email = new Intent(Intent.ActionSend);
// Finish email.
email.PutExtra(Intent.ExtraSubject, emailContent.Subject);
email.PutExtra(Intent.ExtraText, emailContent.Body);
email.SetType("message/rfc822");
email.AddFlags(ActivityFlags.NewTask);
Context context = Android.App.Application.Context;
context.StartActivity(email);
sendWasSuccessful = true;
return Task.FromResult(new Tuple<bool, string>(sendWasSuccessful, errorMessage));
}
catch(Exception ex)
{
errorMessage = ex.Message;
return Task.FromResult(new Tuple<bool, string>(sendWasSuccessful, errorMessage));
}
}