Jens Klingenberg

Xamarin Forms: Call native code with DependencyService

Posted on September 10, 2016  •  1 minutes  • 125 words
Table of contents

Sometimes you need to use platform specific code in Xamarin Forms. To do this you can use DependencyService. In this example i want to show how you can call an Android specific mail intent.

1) Create an interface in your project folder

using System;
namespace Dependencytest
    public interface IMailIntent
        void sendIntent(string mail);

2) Create a class in your Droid Folder that implements the interface

[assembly: Xamarin.Forms.Dependency(typeof(MailIntent))]
namespace Dependencytest.Droid
	public class MailIntent : IMailIntent
		public void sendIntent(string mail)
			var intent = new Intent(Intent.ActionSend);
			intent.PutExtra(Intent.ExtraEmail, new[] { "" });
			Forms.Context.StartActivity(Intent.CreateChooser(intent, "Send email"));

Don’t forget the assembly annotation

3) Use DependencyService

Now you can use the DependencyService in your shared code to call the native function
Let's connect: