Xamarin.Forms Android implementation


Example

The Android specific implementation is a bit more complex because it forces you to inherit from a native Java.Lang.Object and forces you to implement the IOnInitListener interface. Android requires you to provide a valid Android context for a lot of the SDK methods it exposes. Xamarin.Forms exposes a Forms.Context object that provides you with a Android context that you can use in such cases.

using Android.Speech.Tts;
using Xamarin.Forms;
using System.Collections.Generic;
using DependencyServiceSample.Droid;

public class TextToSpeechAndroid : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
{
    TextToSpeech _speaker;

    public TextToSpeechAndroid () {}

    public void Speak (string whatToSay)
    {
        var ctx = Forms.Context;

        if (_speaker == null) 
        {
            _speaker = new TextToSpeech (ctx, this);
        } 
        else 
        {
            var p = new Dictionary<string,string> ();
            _speaker.Speak (whatToSay, QueueMode.Flush, p);
        }
    }

    #region IOnInitListener implementation
    
    public void OnInit (OperationResult status)
    {
        if (status.Equals (OperationResult.Success)) 
        {
            var p = new Dictionary<string,string> ();
            _speaker.Speak (toSpeak, QueueMode.Flush, p);
        }
    }
    
    #endregion
}

When you've created your class you need to enable the DependencyService to discover it at run time. This is done by adding an [assembly] attribute above the class definition and outside of any namespace definitions.

using Android.Speech.Tts;
using Xamarin.Forms;
using System.Collections.Generic;
using DependencyServiceSample.Droid;


[assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechAndroid))]
namespace DependencyServiceSample.Droid {
    ...

This attribute registers the class with the DependencyService so it can be used when an instance of the ITextToSpeech interface is needed.