Search code examples
androidgpstext-to-speech

How to turn Android text-to-Speech inside GPS LocationListener?


Is it possible to turn the text to speech feature on inside the LocatioListener class??

I'm trying to make an android application detect how far you have moved. I am able to turn on the GPS, and monitor for location movement. I would like to make it say "You have moved 300meters". It would be very convenient to put it inside the OnLocation method, but it complains when i try to instantiate the texttospeech??

This is what I was trying:

public class Location implements LocationListener {
    static TextToSpeech talk;
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

//This yells at me on next line, won't let me use 'this' as context?? (Also tried Location.this)

        talk = new TextToSpeech(this, new extToSpeech.OnInitListener() {
        public void onInit(int status) {
            // TODO Auto-generated method stub

            talk.setLanguage(Locale.UK);
            Location aloc = new Location("aloc");
            Location bloc = new Location("bloc");
            aloc.setLatitude(alat);
            aloc.setLongitude(alon);
            bloc.setLatitude(blat);
            bloc.setLongitude(blon);

            float distance = aloc.distanceTo(bloc);
            talk.speak("You Moved..", TextToSpeech.QUEUE_FLUSH, null);
            }
    });     


}

public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

Solution

  • You will need a reference to a Context in order to initialise the TTS engine. Hence it will not work with this or Location.this, since both refer to the running instance of your Location class, which obviously is not a Context (or subclass of it).

    That being said, there are multiple options.

    1. If you use your Location class as anonymous innerclass or non-static innerclass in e.g. an Activity (or any other class where you can get a reference to a Context object), you can use a reference to the outer class to initialise the TTS engine.
    2. In stead of trying to initialise the TTS engine directly inside the Location class, initialize it somewhere where you do have a Context reference; e.g. the same place where you request the LocationManager (for which you already need a Context reference).
    3. Create a centralized instance of the TTS engine. You could set it up as singleton, but can also subclass Application and keep it around there. After it has been initialized, you can get and use it more or less anywhere you like.